我有GridView:
<asp:GridView ID="MyGridView" runat="server" ShowFooter="true"
AutoGenerateColumns="False" Visible="True">
<Columns>
<asp:BoundField DataField="id" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="fullName" />
<asp:TemplateField HeaderText="situation>">
<ItemTemplate>
<asp:DropDownList ID="dl_situation" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="procesVerbal">
<ItemTemplate>
<asp:TextBox ID="tbNr" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Data">
<ItemTemplate>
<asp:TextBox ID="tbDate" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
现在我想用数据库中的数据填充这个Grid,我有一个方法可以返回带有我所有数据的数据
当我填写mygrid时:
MyGridView.DataSource = dataTable;
MyGridView.Databind();
在这种情况下,所有TextBoxes和DropDownList都为空。
在下面的代码中,我正在尝试创建一个从数据库接收DataTable并使用数据填充gridview的函数。如何为dataTable.Rows创建foreach语句,将TextBox元素和selectedIndex值分配给DropDownList?
protected bool FillGridWithData(DataTable dataTable)
{bool result;
try
{
foreach (GridViewRow row in MyGridView1.Rows)
{
if (row.RowType != DataControlRowType.DataRow) break;
var ddl = (DropDownList)row.FindControl("dl_situation");
if (ddl != null)
{
ddl.DataSource = PublicStatic.Situation;
ddl.DataTextField = PublicStatic.Name;
ddl.DataValueField = PublicStatic.Code;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem(String.Empty, String.Empty));
ddl.SelectedIndex = //data from datatable;
}
var tb1 = (TextBox)row.FindControl("tbNr");
if (tb1 != null)
tb1.Text =//data from datatable;
var tb2 = (TextBox)row.FindControl("tbDate");
if (tb2 != null)
tb2.Text = //data from datatable;
}
result = true;
}
catch (Exception exception)
{
result = false;
}
return result;
}
答案 0 :(得分:1)
绑定字段中的DataField
属性必须等于数据表中的column name
。
对于在模板字段中绑定文本框,您可以使用Eval或Bind方法。
示例:强>
<asp:TemplateField HeaderText="procesVerbal">
<ItemTemplate>
<asp:TextBox ID="tbNr" Text='<%# Eval("ColumnName") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
并且为了绑定gridview中的下拉列表,您可以使用单独的sql数据源。并指定dropdownlist DataSourceID,DataTextField和DataValueField属性。
下拉列表示例:
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1" DataTextField="ProductName" DataValueField="ProductID" ></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [ProductName], [ProductID] FROM [Alphabetical list of products]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
如果你想从后面的代码绑定数据源那么你可以使用gridview的RowDataBound
事件
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
TextBox t = (TextBox)e.Row.FindControl("ControlID");
t.Text = "Some Text";
}
}