单击模板字段命令按钮时获取gridview单元格值 [英] getting gridview cell values when clicking template field command button

查看:196
本文介绍了单击模板字段命令按钮时获取gridview单元格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模板字段中有一个带有命令按钮的gridview。
在没有选择行的情况下,如何获取命令按钮上的第一个单元格值?



为了测试,我尝试设置一个标签的文本值,但我认为,行不是先选择,它将无法工作

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


解决方案

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

 < asp:Button ID =Button1CommandArgument ='<%#Container.DataItemIndex%>' OnCommand =Button1_Commandrunat =serverText =Button/> 

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

  protected void Button1_Command(object sender,CommandEventArgs e)
{
Label3.Text =test+ GridView1.Rows [Convert。 ToInt32(e.CommandArgument)]细胞[1]。文本。
}

正如后面发现的那样,您需要将GridView绑定到一个! IsPostBack,否则你会得到一个无效的回发或回调参数错误。

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






lock $ $ $ b $ p注意到搜索GridView像这样的单元格(行[0] .Cells [1] .Text)只有
适用于BoundField列,而不适用于TemplateField和AutoGenerated
列。


I have a gridview with a command button in a template field. Without selecting the row first, how can I grab the first cell value on the command buttons on-click event?

To test, I tried to set a labels text value but I think that as the row is not select first, it won't work

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

解决方案

You can send the row number as a CommandArgument in the button.

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

And grab the correct value from the row and column in code behind.

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

As discovered later, you need to wrap the binding of the GridView into a !IsPostBack, otherwise you'll get an "Invalid postback or callback argument" error.

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

Note that searching GridView cells like this (Rows[0].Cells[1].Text) only works with BoundField columns, not TemplateField and AutoGenerated Columns.

这篇关于单击模板字段命令按钮时获取gridview单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆