Click here to Skip to main content
14,773,203 members
Please Sign up or sign in to vote.
1.33/5 (2 votes)
See more:
I have a dropdown list to search by categories. I need help to bind my gridview at page load, but at the same time, I also have a select command as votes
Posted

Add template field in Gridview Like that
<asp:templatefield headertext="Some Text" xmlns:asp="#unknown">
<itemtemplate>
<asp:dropdownlist id="ddlAnything" runat="server" />
</itemtemplate>
</asp:templatefield>


// In page Load Bing GridView
GridView1.DataSource = <Your DataSource>;
GridView1.DataBind();
 
 
// In RowDataBound Event Of GridView Bind Your DropDown
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
    {
      // your code to get data
         DropDownList ddlAnything= (DropDownList)e.Row.FindControl("ddlAnything");
         ddlAnything.DataSource = dataset.Tables[0].DefaultView;
         ddlAnything.DataValueField = "ValueField";
         ddlAnything.DataTextField = "TextField";
         ddlAnything.DataBind();
    }
}
   
v6
<asp:gridview id="gvUserInfo" runat="server" autogeneratecolumns="false" onrowdatabound="gvUserInfo_RowDataBound" xmlns:asp="#unknown">
<headerstyle backcolor="#df5015" font-bold="true" forecolor="White">
<columns><asp:boundfield datafield="CountryId" headertext="CountryId">
<asp:boundfield datafield="CountryName" headertext="CountryName">
<asp:templatefield headertext="Location">
<itemtemplate>
<asp:dropdownlist id="ddlCity" runat="server" width="100px">





c# code:

qlConnection con =new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// This method is used to bind gridview from database
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select TOP 4 CountryId,CountryName from Country", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();

}

protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
con.Open();
var ddl = (DropDownList)e.Row.FindControl("ddlCity");
int CountryId = Convert.ToInt32(e.Row.Cells[0].Text);
SqlCommand cmd = new SqlCommand("select * from State where CountryID=" + CountryId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl.DataSource = ds;
ddl.DataTextField = "StateName";
ddl.DataValueField = "StateID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("--Select--", "0"));
}
}


try this
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900