我正在使用gridview在asp.net网站上工作。
gridview包含来自sql数据库的数据。
像:
Cuntry----Name
USA--------John
England----Frank
...
数据加载到gridview中,如下所示:
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_loadData";
sqlConn.Open();
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
因此,在名称列中,我想要一个下拉列表。我希望下拉列表中包含所选数据库中的相应值。
我该怎么做?
由于
答案 0 :(得分:1)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:DropDownList Width="50" runat="server" id="ddlCountry" AutoPostBack="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
在代码隐藏
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Checking whether the Row is Data Row
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Finding the Dropdown control.
Control ctrl = e.Row.FindControl("ddlCountry");
if (ctrl != null)
{
DropDownList dd = ctrl as DropDownList;
//Here Bind with country list
dd.DataSource = lst;
//Put here the object properties name
dd.DataValueField = "idCountry";
dd.DataTextField = "nameCountry";
dd.DataBind();
//Here add the code to select the current user country in the list
int idUserCountry = 10;
dd.Items.FindByValue(idUserCountry).Selected = true;
}
}
}