开发者

gridview issue when trying to get element from a row

I have a gridview which successfully binds to the database and gets all dat开发者_如何学Pythona. Now I have added a link button in one of the coloumns which does this:

GridViewRow grow = gvInbox.SelectedRow;            
DataRow dr = ((DataTable)this.gvInbox.DataSource).Rows[grow.DataItemIndex];
int MessageId = (int)dr["MessageId"];
Response.Write(MessageId);

Basically I am trying to get the datarow and get a MessageID. However the second line from above gives me outofbound exception.


I think your typecasting is slightly off... You need to get the entire object that represents the data source...

yours... ((DataTable)this.gvInbox.DataSource).

should be (DataTable)(this.gvInbox.DataSource).

So you are typecasting the "this.gvInbox.DataSource" which is the datatable, then getting the .Rows[ ] reference from that.

Otherwise, its interpreting your typecasting like this.

((DataTable)(this).gvInbox.DataSource).


A better way is to have your ID as DataKey in your GridView markup:

DataKeyNames="MessageId"

Then in your code behind you can reference it:

if(gvInbox.SelectedIndex > -1)
    MessageId = (int) gvInbox.DataKeys[gvInbox.SelectedIndex].Value;

Keep in mind that the DataTable will not be there on a postback. So to get data "out" of a GridView cell that is not a DataKey you see code like:

gvInbox.Rows[gvInbox.SelectedIndex].Cells[4].Text
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜