Google
 

Tuesday, March 18, 2008

Dynamically Populating a Gridview with a Search Button and aTextbox

This snippet shows you a simple way to dynamically populate a GridView with a search button and a textbox. Your SQL Select statement will determine which columns you want displayed in your GridView.

//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)
{
Label1.Text =
"0";
}

protected void Button1_Click(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 c
olumns you want to be displayed
//If you use the select all (*) it will obviously display all the columns
//Don't forget to concatenate when using TextBox1.Text
SqlDataAdapter da= new SqlDataAdapter("SELECT columname FROM tablename WHERE VendorID LIKE '" + TextBox1.Text + "', cn);
// Fill the Data Adapter
da.Fill(ds);

//Set the Datasource for the Repeater equal to the DataSet
GridView1.DataSource = ds;
//Bind your Data
GridView1.DataBind();

Label1.Text = GridView1.Rows.Count.ToString();
}

*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. 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.

0 comments: