0
如果我想在GridView
中填充DropdownList
什么将是最好的方法?使用GridView
'OnRowDataBound
'事件并且每次都提取查询到数据库或首先获取所有数据并将其放在数据表上并从该数据表中继续工作?GridView中填充下拉列表的方法
如果我想在GridView
中填充DropdownList
什么将是最好的方法?使用GridView
'OnRowDataBound
'事件并且每次都提取查询到数据库或首先获取所有数据并将其放在数据表上并从该数据表中继续工作?GridView中填充下拉列表的方法
由于您的问题不清楚您的要求,我假定您想要使用gridview的OnRowDataBound
事件在Gridview
内绑定dropdownlist
。
所以这里的步骤: -
DropDownList
在TemplateField
ItemTemplate
添加一个GridView控件的HTML。<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField HeaderText="Name" DataField="ContactName" />
<asp:TemplateField HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>' Visible = "false" />
<asp:DropDownList ID="ddlCountries" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
然后,你需要的gridview
与将来自于数据库中的记录进行绑定。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT ContactName, Country FROM Customers");
GridView1.DataBind();
}
}
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
然后为OnRowDataBound
代码将遵循如下图所示: -
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
//Select the Country of Customer in DropDownList
string country = (e.Row.FindControl("lblCountry") as Label).Text;
ddlCountries.Items.FindByValue(country).Selected = true;
}
}
供您参考,请参阅Reference link
另见Working demo供您参考
希望有所帮助。
你的问题是什么? ? – BNN