如何在gridview中显示列表框项 [英] how to show the listbox item in gridview
本文介绍了如何在gridview中显示列表框项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在gridview中显示列表框项
how to show the listbox item in gridview
推荐答案
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="false" onrowdatabound="OnRowDataBound" xmlns:asp="#unknown">
<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>
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;
}
}
}
}
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;
}
}
这篇关于如何在gridview中显示列表框项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文