开发者

firing problem of selected_indexchanged(cant even print cell value in grid view by any event)

//code in aspx.

<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="MobilePhon开发者_开发知识库e" 
    HeaderText="Mobile Phone" />
        <asp:ButtonField Text="Button" ButtonType="Button" CommandName="Select" />
</Columns>
</asp:GridView>
   <asp:Label ID="Label" runat="server" Text="Label"></asp:Label>

//code behind file()

protected void grid_SelectedIndexChanged(object sender, 
EventArgs e)
{
int selectedRowIndex;
selectedRowIndex = grid.SelectedIndex;
GridViewRow row = grid.Rows[selectedRowIndex];
string name = row.Cells[0].Text;
Label.Text = "You selected " + name + ".";
}

Q: iam not even able to print the selected row.If anyone could help me with this issue.


You should really be getting this value from the underlying data item. But, if for some reason that value is being manipulated after it has been data-bound and you need to get the actual value of the control in that cell then you probably want something like this:

    protected void grid_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = (GridViewRow)grid.Rows[grid.SelectedIndex];
        string name = ((Label)row.Cells[1].Controls[1]).Text;
        Label.Text = "You selected " + name + ".";
    }

but... that's a pretty messy way of achieving this. Also "Label" is a pretty bad name for a label. Also, Cell[0] like you posted is going to be the column with the select button most likely, not the column with the value you want. And, once you're in the correct cell, there are 3 controls, 2 literals and a label for a normal boundfield. Control[1], the second control, is the label control that will have the value you're looking for.


You have to use a RowCommand Event instead of a SelectedIndexChanged Event.

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Select")
    {
        GridViewRow row = ((GridViewRow)((Button)e.CommandSource).NamingContainer);
        string name = row.Cells[0].Text;
        Label.Text = "You selected " + name + ".";
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜