How to use GridView and DataSets in C#.NET 2.0?

Question -

I need a example of how to create a gridview in .cs versus just dragging and dropping the gridview on the aspx page?

I created a dataset and called a stored procedure using data adapter, but i do not know how to data bind the data set into the grid view I have.

It seems everywhere I search the gridview examples they have is just dragging and dropping to the page and configuring a datasource.
Answer -

//connect to database via dataset & dataadapte
SqlConnection con = new SqlConnection("server=localhost;Initial Catalog=databasename;uid=;pwd=;");
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("stored proc name", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds);

//create gridview by code & bind dataset to it
GridView g = new GridView();
Page.Controls.Add(g);
g.DataSource = ds;
Page.DataBind();

2 comments:

  1. How to use this code for connect to remorte database server.

    ReplyDelete
  2. Is very easy,

    SqlConnection con = new SqlConnection("server=localhost;Initial Catalog=databasename;uid=;pwd=;");

    set your database sever address for server property.

    ReplyDelete

Thank you very much