I have 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>
Now I want to fill this Grid with data from database, I have one method that returns datatable with all my data
when I fill mygrid:
MyGridView.DataSource = dataTable;
MyGridView.Databind();
in this case all TextBoxes and DropDownList are null.
In the code below I'm trying to create a function that receives DataTable from database and populates gridview with data. How do I make a foreach statement for dataTable.Rows that will assign text values to TextBox elements and selectedIndex value to 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;
}