简体   繁体   English

如何获取GridView中单元的值?

[英]How do I get the value of a Cell in a GridView?

I have review various questions here, regarding this, however I still cannot get this to work. 我已经在这里查看了关于此的各种问题,但是我仍然无法解决这个问题。

I have a grid view ( OrderList ) and in this gridview I have a column with a button to simply update a particular field (basically mark an order as accepted). 我有一个网格视图( OrderList ),在这个网格视图中,我有一列带有按钮的按钮,可以简单地更新特定字段(基本上将订单标记为接受)。

In the aspx file I have the following code 在aspx文件中,我有以下代码

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="ButtonToAcceptOrder" runat="server" Text="Accept Order" CommandName="AcceptOrder" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
    </ItemTemplate>
</asp:TemplateField>

In the code Behind file, I have the following code: 在代码隐藏文件中,我有以下代码:

protected void OrderList_RowCommand(object sender, GridViewCommandEventArgs e)
{
     if (e.CommandName =="AcceptOrder")
     {
          // Retrieve the row index stored in the 
          // CommandArgument property. 
          int index = Convert.ToInt32(e.CommandArgument);

          // Retrieve the row that contains the button 
          // from the Rows collection.
          GridViewRow row = OrderList.Rows[index];

          Int32 oId = Int32.Parse(row.Cells[1].Text);

          //Code to Update database by order id
     }
}

The error is coming from oId telling that the input is not in the correct format. 错误来自oId指示输入格式不正确。
In the first column of the gridview I am displaying the ID of that I require. 在gridview的第一列中,我正在显示所需的ID Whilst the other columns are showing the other details. 而其他列则显示其他详细信息。

If you spot any problems in my code can you kindly help? 如果您发现我的代码中有任何问题,可以为您提供帮助吗?

(I have previously followed this tutorial: http://msdn.microsoft.com/en-us/library/vstudio/bb907626(v=vs.100).aspx ) (我以前已经按照本教程进行操作: http : //msdn.microsoft.com/zh-cn/library/vstudio/bb907626 (v= vs.100 ) .aspx

If you have an unique id for each row, then you should be using the DataKeyNames property of the GridView. 如果每一行都有唯一的ID,则应该使用GridView的DataKeyNames属性。

<GridView id="OrderList" DataKeyNames="oId"... />

Then in your RowCommand code, access it like this: 然后在您的RowCommand代码中,像这样访问它:

Int32 oId = OrderList.DataKeys[row.DataItemIndex].Value;

This is much cleaner than trying to get value from a cell. 这比尝试从单元中获取价值要干净得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM