Get GridView Cell Value Knowing Row And Column Index Only

故事扮演 提交于 2019-12-23 04:29:14

问题


I think my question title is quite straight forward.

Any help is appreciated..


回答1:


With BoundField and in readonly mode you can use GridView1.Rows[x].Cells[x].Text but with edit mode you have to use Controls collection to get reference of a control. This method returns a Control object.

Control control=GridView1.Rows[x].Cells[x].Controls[0]; // later you may cast it to appropriate control class.

If template field is used then you have to issue FindControl method from the Cells collection to get reference of a control based upon its ID. You may also use Cells[x].Controls collection too.

Control control=GridView1.Rows[x].Cells[x].FindControl("ID_Of_Control"); // later you may cast it to appropriate control class.

EDIT:

It is also possible that there can be one or more controls having same name/ID across the Templatefields. In that case you can't use FindControl method.

Example:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" Text="Button" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" Text="Button" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Now to get Button and change its text from 2nd row and 1st cell:

 Button btn = GridView1.Rows[1].Cells[0].Controls[1] as Button ;
 if(btn!=null)
    btn.Text = "Hello";



回答2:


If it's a BoundField you could do

gv.Rows[1].Cells[1].Text;

If it's a TemplateField, you have to get the control that has the value you want.

Label L = gv.Rows[1].FindControl("yourcontrolId") as Label;
L.Text;


来源:https://stackoverflow.com/questions/8640532/get-gridview-cell-value-knowing-row-and-column-index-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!