采用asp:BoundColumn列
前台:
<asp:BoundColumn DataField="UserID" HeaderText="工号">
后台:
foreach (DataGridItem item in dataGrid.Items)
{
string userID = item.Cells[1].Text;
}
这样的弊端就是如果列的索引发生变化,就导致读取不到对应的列所对应的单元格值。
最佳方法应该采用asp:TemplateColumn模板列的方式
参考:http://blog.csdn.net/aiouwen521/article/details/8490742
前台:
<asp:TemplateColumn>
<ItemTemplate>
<asp:TextBox Runat="server" ID="txtID" Text='<%# DataBinder.Eval(Container.DataItem,"au_id") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
后台:
读取DataGrid控件TextBox值
foreach(DataGrid dgi in yourDataGrid.Items)
{
TextBox tb = (TextBox)dgi.FindControl("yourTextBoxId");
tb.Text....
}
针对TemplateColumn 优雅写法:
List<RollLeaveDetailCom> rollLeaveDetailComList = new List<RollLeaveDetailCom>();
foreach (DataGridItem item in this.gridDetails.Items)
{
RollLeaveDetailCom leaveDetailCom = new RollLeaveDetailCom();
leaveDetailCom.StartDate = Convert.ToDateTime(item.ValueOf("txtStartDate"));
leaveDetailCom.StartTime = item.ValueOf("txtStartTime");
leaveDetailCom.EndDate = Convert.ToDateTime(item.ValueOf("txtEndDate"));
leaveDetailCom.EndTime = item.ValueOf("txtEndTime");
leaveDetailCom.TotalDay = item.ValueOf("txtTotalTime").Replace("天", "").ToInt();
leaveDetailCom.SalaryDay = item.ValueOf("txtSalaryTime").Replace("天", "").ToInt();
rollLeaveDetailComList.Add(leaveDetailCom);
}
return rollLeaveDetailComList;
/// <summary>
/// 扩展 DataGridItem, 取其内部控件的值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
/// <param name="ctrlId"></param>
/// <returns></returns>
public static string ValueOf(this DataGridItem item, string ctrlId)
{
if (item == null || string.IsNullOrEmpty(ctrlId)) return string.Empty;
Control ctrl = item.FindControl(ctrlId);
string result = string.Empty;
if (ctrl is TextBox)
result = (ctrl as TextBox).Text;
else if (ctrl is HyperLink)
result = (ctrl as HyperLink).Text;
else if (ctrl is LinkButton)
result = (ctrl as LinkButton).Text;
else if (ctrl is HiddenField)
result = (ctrl as HiddenField).Value;
else if (ctrl is DropDownList)
result = (ctrl as DropDownList).SelectedValue;
return result;
}
注意:BoundColumn列转换为TemplateColumn 可以通过DataGrid的属性编辑器可视化UI设计窗口进行转换。