【问题标题】:getting gridview cell values when clicking template field command button单击模板字段命令按钮时获取gridview单元格值
【发布时间】:2016-08-21 17:52:25
【问题描述】:

我在模板字段中有一个带有命令按钮的网格视图。 在不先选择行的情况下,如何在命令按钮单击事件中获取第一个单元格值?

为了测试,我尝试设置标签文本值,但我认为由于没有先选择该行,所以它不起作用

Label3.Text = "test " + GridView1.SelectedRow.Cells[1].Text;

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    您可以在按钮中将行号作为 CommandArgument 发送。

    <asp:Button ID="Button1" CommandArgument='<%# Container.DataItemIndex %>' OnCommand="Button1_Command" runat="server" Text="Button" />
    

    并从后面代码中的行和列中获取正确的值。

    protected void Button1_Command(object sender, CommandEventArgs e)
    {
        Label3.Text = "test " + GridView1.Rows[Convert.ToInt32(e.CommandArgument)].Cells[1].Text;    
    }
    

    正如稍后发现的,您需要将 GridView 的绑定包装到一个 !IsPostBack 中,否则您将收到“Invalid postback or callback argument”错误。

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = myDataSource;
            GridView1.DataBind();
        }
    }
    

    请注意,仅像这样 (Rows[0].Cells[1].Text) 搜索 GridView 单元格 适用于 BoundField 列,而不是 TemplateField 和 AutoGenerated 列。

    【讨论】:

    • 感谢您抽出宝贵时间回复。我尝试了你的建议,得到了这个错误......“无效的回发或回调参数。事件验证是使用配置中的 或页面中的 启用的。出于安全目的,此功能验证回发或回调事件的参数是否源自最初呈现它们的服务器控件。如果数据有效且符合预期,请使用 ClientScriptManager.RegisterForEventValidation 方法注册回发或回调数据以进行验证。 "
    • Weird... 在这里工作,enableEventValidation=trueenableEventValidation=false 在页面指令中。
    • 我需要 enableEventValidation=false 否则会出现上述错误,如果为 false 则没有错误但事件似乎没有触发。
    • 发现我认为的错误,尝试将网格的DataBinding包装成if (!Page.IsPostBack) { }。当我删除它时,我得到了同样的错误。我花了一段时间才弄清楚。其次,我忘了提到使用Cells[1].Text; 仅适用于boundfield,而不适用于模板。请参阅我对这个问题的回答 stackoverflow.com/questions/39008313/searching-a-nested-gridview-asp-net。
    • 刚刚开始测试这个,并通过一些调整得到了我所需要的,所以如果你想把这个作为答案发布,我会接受它。谢谢
    猜你喜欢
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2023-03-17
    相关资源
    最近更新 更多