Thursday, January 24, 2008

Binding the Header of GridView even if there is no result in datatable

//Fill the GridView dynamically ...
private void FillGridView(string Ids)
{
string str = "SQL Query";

DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(str, sqlcon);
da.Fill(dt);

if (dt.Rows.Count == 0)
{
// Remove contraints so an empty row can be added...
dt.Constraints.Clear();
foreach (DataColumn dc in dt.Columns)
dc.AllowDBNull = true;

// Add a blank row to the dataset...
dt.Columns[0].AllowDBNull = true;
dt.Rows.Add(dt.NewRow());

// Bind the DataSet to the GridView...
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();

// Get the number of columns to know what the Column Span should be...
int columnCount = GridView1.Rows[0].Cells.Count;

// Call the clear method to clear out any controls that you use in the columns. I use a dropdown list in one of the column so this was necessary....
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columnCount;
GridView1.Rows[0].Cells[0].Text ="Nothing Selected!";
}
else
{
//Clear the databinding ...
GridView1.DataSource = null;
GridView1.DataBind();

//Rebind with the database ...
GridView1.DataSource = dt;
GridView1.DataBind();
}

}

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

No comments: