Reputation: 5539
I am trying to create nested comments. The below code is giving me Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
protected void GridViewRowCommand(Object sender, GridViewCommandEventArgs e)
{
var scrapId = Int32.Parse(e.CommandArgument.ToString());
switch (e.CommandName)
{
case "comment":
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridViewUserScraps.Rows[index];
TextBox txtcomment = (TextBox)GridViewUserScraps.Rows[index].FindControl("txtcomment");
string postcomment = "Insert INTO comment (FromId,ToId,PostId,CommentMsg) VALUES('" + Session["UserId"].ToString() + "','" + Request.QueryString["Id"].ToString() + "','" + scrapId + "','"+txtcomment.Text+"')";
dbClass.ConnectDataBaseToInsert(postcomment);
break;
}
}
The datakeyname is .. DataKeyNames="ScrapId"
I wan to pass the values of textbox which lies in the same row as the button which i click to post.
Button:
<asp:Button ID="Button1" runat="server" Text="Comment" CommandName="comment"
CommandArgument='<%# Eval("ScrapId")%>' />
Upvotes: 0
Views: 487
Reputation: 4094
Try to get the row index like:
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int index = gvr.RowIndex;
Generally the commandArgument
contains the rowIndex by default, but in your case, you are overwriting it in your tag, with the Eval("ScrapId")
.
The e
is an object containing information about the event that was fired. ComandSource
is the source control that fired the event, in your case, the Button, so we cast is to Button.
Than, we have the NamingContainer
, that is the server control that wraps your Button, in this case a GridViewRow
.
With the GridViewRow
, we have access directly to the active row at the time of the event, and there we have more data about the row, including the current RowIndex
Upvotes: 2