arun kumar

arun kumar

  • NA
  • 18
  • 21.8k

How to pass autogenerate gridview column names in view states

Nov 21 2012 2:56 AM
How to pass autogenerate gridview column names in view states??? Number of Columns may be vary depending on table Column.... 
I am Loading Dropdownlist with various table names depending on database.... 
On selecting particular table grid view will be generated... And Column names may be vary depending on Table.... 
Now I want to get All Column Names in View State... How to get that??? 
//This Populate Grid View will generate gridview for any Table which is selected

private void PopulateGridView() { 
  try {
  SqlConnection con;
  con = new SqlConnection(@"Data Source=CKQJ8433\SQLEXPRESS;" + "Initial Catalog" + "=" +drddatabase.SelectedValue + ";" + "Integrated Security=True");
  SqlCommand cmd = new SqlCommand();
  cmd.CommandText = "select * from " + drdtablename.SelectedValue;
  cmd.CommandType = CommandType.Text;
  cmd.Connection = con;
  SqlDataAdapter da = new SqlDataAdapter();
  da.SelectCommand = cmd;
  DataSet ds = new DataSet();
  da.Fill(ds, "Disp");
  grdview.DataSource = ds.Tables["disp"];
  Label1.Text = " ";
  //View State to Delete Data From Gridview
  ViewState["arun"] = ds;
  string strColumnsName = ds.Tables[0].Columns[0].ColumnName;
  //ViewState to delete Data From Database
  ViewState["id"] = strColumnsName;
  }
  catch (SqlException ex)
  {
  }
  grdview.DataBind();
  }
  protected void grdview_RowEditing(object sender, GridViewEditEventArgs e)
  {
  //This is Data Set Which I got From PopulateGridView
  DataSet dt = (DataSet)ViewState["arun"];
  //In Employee I am Having 3 Columns... So I write this code
  string colname1= dt.Tables[0].Columns[0].ColumnName;
  ViewState["eid"] = colname1;
  string colname2 = dt.Tables[0].Columns[1].ColumnName;
  ViewState["ename"] = colname2;
  string colname3 = dt.Tables[0].Columns[2].ColumnName;
  ViewState["ecity"] = colname3;
  grdview.EditIndex = e.NewEditIndex;
  PopulateGridView();
  }

This For Particular Employee Table which consist of 3 Columns.... 
For Different Table Columns may be vary....

Answers (2)