Monday, August 16, 2010

GridView and DataSets in C#.NET 2.0?

Can anyone give me an 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.





Does anyone know how to do it with a data set?GridView and DataSets in C#.NET 2.0?
//connect to database via dataset %26amp; dataadapter


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 %26amp; bind dataset to it


GridView g = new GridView();


Page.Controls.Add(g);


g.DataSource = ds;


Page.DataBind();GridView and DataSets in C#.NET 2.0?
Dragging and dropping just sets up some basic properties. Load your dataset with data:





grid1.DataSource = yourdataset


grid1.DataMember = yourdataset.datatable (hoisted datatable)


grid1.AutoGenerateColumns = true (this will automatically set up the columns to bind to your datatable)


and most importantly


grid1.Refresh()
You don't really need to use a DataSet. A Datatable would suffice. You can even only use a SqlDataReader.





Here is the complete code:


%26lt;%@ Page Language=';C#'; %%26gt;


%26lt;%@ Import Namespace = ';System.Data'; %%26gt;


%26lt;%@ Import Namespace = ';System.Data.SqlClient'; %%26gt;








%26lt;script runat=';server';%26gt;





protected void Page_Load( object sender, EventArgs e)


{


if ( !Page.IsPostBack ) {


BindGridView();


}


}


private void BindGridView() {


using ( SqlConnection cn = new SqlConnection( ';server=.; uid=sa; pwd=; database=Northwind'; ) ) {


SqlCommand cmd = new SqlCommand( ';GetCustomers'; , cn);


cn.Open();


SqlDataAdapter da = new SqlDataAdapter( cmd );


DataTable dt = new DataTable();


da.Fill(dt);





gv.DataSource = dt;


gv.DataBind();


}


}


%26lt;/script%26gt;





%26lt;html xmlns=';http://www.w3.org/1999/xhtml';%26gt;


%26lt;head runat=';server';%26gt;


%26lt;title%26gt;Untitled Page%26lt;/title%26gt;


%26lt;/head%26gt;


%26lt;body%26gt;


%26lt;form id=';form1'; runat=';server';%26gt;


%26lt;asp:GridView ID=';gv'; runat=';server'; AutoGenerateColumns=';True';%26gt;


%26lt;/asp:GridView%26gt;


%26lt;/form%26gt;


%26lt;/body%26gt;


%26lt;/html%26gt;





To create the stored procedure, simply execute the following T-SQL against the Northwind Sample DB:


CREATE PROCEDURE GetCustomers AS


SELECT * FROM Customers





Hope this helps.
  • web hosting talk
  • loan
  • No comments:

    Post a Comment