C# 从 Gridview 单元格获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15512832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting value from a Gridview cell
提问by JARRRRG
I'm trying to get an int value from a GridView. Here is the screenshot of my gridview.
我正在尝试从 GridView 获取 int 值。这是我的 gridview 的屏幕截图。
Here is the asp code for the Gridview
这是Gridview的asp代码
I have created a RowCommand method where when I press the Remove button on the GridView it is suppose to give me the int value of the 2nd column. So for example if I was to press the last Remove button it would give me an int value of 5.
我创建了一个 RowCommand 方法,当我按下 GridView 上的删除按钮时,它应该给我第二列的 int 值。例如,如果我按下最后一个删除按钮,它会给我一个 int 值 5。
This is my codebehind for the method
这是我的方法的代码隐藏
protected void grdOrder_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Remove")
{
int bigStore = Convert.ToInt32(grdOrder.SelectedRow.Cells[2].Text);
clsStockCollection AnId = new clsStockCollection();
clsStock TheOrder = new clsStock();
TheOrder.OrderId = bigStore;
AnId.DeleteOrder(TheOrder);
DataCall();
}
}
When I run this code I get this error. Object reference not set to an instance of an object.
当我运行此代码时,出现此错误。你调用的对象是空的。
I don't understand how or why I need to reference an object for example : Object As New Object. Why do I need to do this?
我不明白我如何或为什么需要引用一个对象,例如:Object As New Object。为什么我需要这样做?
Here is the codebehind for the full class : pastebin.com/yzLR7s2w
这是完整课程的代码隐藏:pastebin.com/yzLR7s2w
A thanks in advance
提前致谢
采纳答案by Ryan Frame
SelectedRows
only returns rows that have been selected; without a selection you won't get anything. Instead of int bigStore = Convert.ToInt32(grdOrder.SelectedRow.Cells[2].Text);
try:
SelectedRows
只返回已选择的行;没有选择,您将一无所获。而不是int bigStore = Convert.ToInt32(grdOrder.SelectedRow.Cells[2].Text);
尝试:
int rowIndex = Convert.ToInt32(e.CommandArgument); // Get the current row
int bigStore = Convert.ToInt32(grdOrder.Rows[rowIndex].Cells[2].Text);