日期:2014-05-18  浏览次数:20606 次

TemplateField中ListBox问题
在GridView的TemplateField中,想用一个ListBox动态显示一组数据,这组数据是根据当前的绑定Item的Id属性从数据库中取出的,但是好像实现不了,有什么好办法吗?

<asp:GridView ...>
  <Columns>
  ...
  <asp:TemplateField ...>
  <ItemTemplate>
  <asp:ListBox ... /> <--此处不知如何实现--
...

------解决方案--------------------
可以实现,在RowBound事件里,取出id,然后在次读数据库,绑定listbox
------解决方案--------------------
前台:
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" />
<asp:TemplateField><ItemTemplate><asp:ListBox runat="server" ID="ListBox1" AutoPostBack="true" OnTextChanged="ListBox1_SelectedIndexChanged"></asp:ListBox></ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>

</div>
</form>

.cs文件

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = SqlClass.getDataTable("select top 10 ID from [user]");
GridView1.DataBind();
}
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string strID = e.Row.Cells[0].Text;
ListBox lb = (ListBox)(e.Row.Cells[1].FindControl("ListBox1"));
lb.DataSource = SqlClass.getDataTable("select ID,UserName from [user] where ID ="+strID);
lb.DataTextField = "UserName";
lb.DataValueField = "ID";
lb.DataBind();
}
}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{

Response.Write(((ListBox)sender).Text);
}