Google
 

Monday, March 17, 2008

Dynamically Populating a DataList with SQL Data Adapter

This snippet shows you a simple way to dynamically populate a DataList. Your SQL Select statement will determine which columns you want displayed in your DataList.

//declare two variables - one for the connection string and the other for the dataset
private String cnstr;
private DataSet ds;

protected void Page_Load(object sender, EventArgs e)
{
// Setup Connection string
cnstr= "server=type in IP address;user=type in database user;password=type in database password;"
+ "database=type in database
name;"
;

// Create a new Sql Connection

SqlConnection cn = new SqlConnection(cnstr);

//Create the DataSet
ds = new DataSet("ds");

//Create a new Sql Data Adapter
//In your SQL Select statement, only select the columns you want to be displayed
//If you use the select all (*) it will obviously display all the columns

SqlDataAdapter da= new SqlDataAdapter( "Your Select Statement" , cn);
// Fill the Data Adapter
da.Fill(ds);

//Set the Datasource for the DataList equal to the DataSet
DataList1.DataSource = ds;
//Bind your Data
DataList.DataBind();
}

*Quick Note: Don't forget to add 'using System.Data.SqlClient;' to the top of the code behind page.

In your .aspx page add the following code in between the body tags. Depending on how many feilds/columns you want to display, will determine how many controls you use. In this example I use a Label to display the data, you don't have to use a Label, you can use another control, such as a TextBox, if you choose to. Click on the image to view full size.

If you have any questions or there are discrepancies in the code please feel free to leave a comment and I will try to answer/fix them as soon as I can.

3 comments:

mejaz said...

Very Great and simple to understand...Thanks

mejaz said...

Very nice...
simple to understand..
thanks

Anonymous said...

how to populate all columns,that may change time to time