你是如何绑定数据的? (对象 datsource、sql 数据源、数据源/数据绑定等)如果您想要用于绑定 gridview 的实际数据,则需要从数据源中获取。
gv.Rows[row].Cells[col]
将为您提供所选 gridview 行中显示的内容,但这将包括您的模板显示的任何内容,而不仅仅是数据。
一种解决方案是将主键作为网格视图中选择按钮的命令参数传递,然后当您选择网格视图时,它会在数据表中搜索该记录,然后您可以在文本框等中显示该数据。
将 select btn col 添加到 gridview:
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="btnSelect" Text="Select" CommandName="Select" CommandArgument='<%#Eval("Month")%>'/>
</ItemTemplate>
</asp:TemplateField>
添加到网格视图:
OnRowCommand="gvReport_OnRowCommand"
文本框:
<asp:TextBox runat="server" ID="txtPerson" />
代码隐藏:
在此示例中,“月份”在我的数据中是唯一的,SessionDataTbl 是我用来绑定 gridview 的数据表。
protected void gvReport_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//Find row data
foreach (DataRow row in SessionDataTbl.Rows)
{
if (row["Month"].Equals(e.CommandArgument))
{
txtPerson.Text = row["Person"].ToString();
//other text boxes, etc.
break;
}
}
//Add row color change
Button btn = e.CommandSource as Button;
if (btn != null)
{
System.Web.UI.Control field = btn.Parent;
if (field != null)
{
GridViewRow row = field.Parent as GridViewRow;
if (row != null)
{
const string backColor = "background-color";
//Remove any previous backcolor
foreach (GridViewRow rw in gvReports.Rows)
{
rw.Style.Remove(backColor);
}
row.Style.Add(backColor, "yellow");
}
}
}
}
}
此示例使用手动数据绑定,但这也可以使用对象数据源等来完成,但您必须在对象数据源 Selected 事件中捕获数据表(如果需要可以提供示例)
注意:此示例必须启用 gridview 视图状态