Hello this code will show on how to Load a Data in gridview and if the record was not found the header of the gridview will automatically show without a html tags in your gridview emptydatatemplate.
Follow these step:
1. Suppose you have a gridview in your web form. Create a connection string. string DBADDRESS = "Data Source=Sai\\SQLEXPRESS;Initial Catalog=SampleSai;Integrated Security=True";
2. The function for your gridview data fill.
public void FillGrid(GridView gridview, DataSet ds) { //Check if Dataset have records if (ds.Tables[0].Rows.Count == 0) { //Add new row ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
//count the cells in rows int columnCount = gridview.Rows[0].Cells.Count;
//clear first the cells in rows, then will add new table cell in each row. The columnspan will be equal to columncount to create a column header in gridview. Then the Cells Text will show. gridview.Rows[0].Cells.Clear(); gridview.Rows[0].Cells.Add(new TableCell()); gridview.Rows[0].Cells[0].ColumnSpan = columnCount; gridview.Rows[0].Cells[0].Text = "" + "No Records Found" + "";
//Fill the GridView. gridview.DataSource = ds; gridview.DataBind();
} //If Datatable have records, fill gridview with records else { //Fill the GridView. gridview.DataSource = ds; gridview.DataBind(); }
}
3. Suppose you have a event that fill data in a gridview.
private void WithRecord() { //Create a new sqlconnection then open the connection. SqlConnection conn = new SqlConnection(DBADDRESS); conn.Open();
//sql statement that will select the data from database table. string sSQL = "Select studentID,studentName from StudentList";
//Create dt as Datatable DataTable dt = new DataTable(); //Create a sql command and Data adapter SqlCommand sCMD = new SqlCommand(sSQL, conn); SqlDataAdapter sDA = new SqlDataAdapter(); sDA.SelectCommand = sCMD; sDA.Fill(dt);
//Now fill Data in your gridview FillGrid(GridView1, dt); }
Hope this simple article will help many.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|