Asp.net GridView : Populate dropdown list base on another drop down list in Editmode

This question was asked from me in interview in a company which works specifically in asp.net. And I was clueless about it. So, i thought that i will add this code in my blog.

try this example:

ASPX






A

B

C






RELEVANT CODE:



private DataTable BindDropDownList(string field)
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT * FROM TableName WHERE Field1 = @Value";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlCmd.Parameters.AddWithValue("@Value", field);
sqlDa.Fill(dt);
}

catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}

return dt;

}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl1 = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl1.NamingContainer;
if (row != null)
{
DropDownList ddl2 = (DropDownList)row.FindControl("DropDownList3");
{
//call the method for binding the second DDL based on the selected item on the first DDL
DataTable dt = BindDropDownList(ddl1.SelectedItem.Text);
ddl2.DataTextField = "Field1";
ddl2.DataValueField = "Field2";
ddl2.DataBind();
}
}
}

Comments

you can use the below url for more details

http://forums.asp.net/t/1421788.aspx/1

Popular posts from this blog

Authorize.net Integration eCommerce Payment Gateway ( Direct Post Method New! )

Get Organised with OneNote

Test your Sql Query Online