获取ASP.net C#中网格视图中列的值/文本以显示在标签中

本文关键字:文本 标签 显示 net ASP 中网 视图 网格 获取 | 更新日期: 2023-09-27 18:26:00

我有一个gridview,它有一个推销员姓名列表。当使用Grid中的ButtonFieldTemplate选择Salesman时。我需要所选销售人员的姓名出现在Label中。

到目前为止,我有这个,但它不起作用:

protected void gvSalesmanByManager_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    lblSalesmanCustomers.Text = gvSalesmanByManager.SelectedValue + "'s Customers"; 
} 

它没有抛出任何错误。甚至连Visual Studio中的红色曲线都没有。这根本不起作用。

我如何在ASP.net和C#4.0中实现这一点。

获取ASP.net C#中网格视图中列的值/文本以显示在标签中

关于文档,SelectedValue获取GridView控件中所选行的数据键值。您的GridView是否包含带键的列?您是否设置了dataKeyNamesProperty(例如datakeynames="myID")?

编辑:要访问列的值,可以使用SelectedRow:

GridViewRow row = GridView1.SelectedRow;
lblSalesmanCustomers.Text = row.Cells[2].Text;

第2版:当您想要读取模板字段时,有两个选项。您可以将值存储在其他不可见列中,也可以访问模板字段中的控件。像这样的东西应该起作用:

lblSalesmanCustomers.Text = ((TextBox)row.Cells[2].FindContol("tbxName")).Text;

确保在页面加载事件中没有分配空文本。或者您需要将这些初始化放在if(!Page.IsPostback)块

到目前为止我的代码:protected void gvSalesmanByManager_SelectedIndexChanged(object sender,EventArgs e){lblSalesmanCustomers.Text=gvSalesman ByManager.SelectedValue+"’s Customers";}–

在事件"gvSalesmanByManager_SelectedIndexChanged"中尝试以下代码:

lblSalesmanCustomers.Text=gvSalesmanByManager.SelectedRow.Cells[0].Text;

你说了一些关于"ButtonFieldTemplate"的内容,请给我看看你的ascx文件中的一些代码,我认为这会对我们有很大帮助。

*编辑:"控制[1]"必须是不对的。但是0是一个文字。您还可以调试代码并设置断点。会容易得多。使用链接按钮尝试此操作:LinkButton lnk1=gvSalesmanByManager.SelectedRow.Cells[0]。Controls[1]作为LinkButton;lblSalesmanCustomers.Text=lnk1.Text;

致以最良好的问候,无