Get the value of a BoundField from a DetailsView

Ray picture Ray · Dec 5, 2013 · Viewed 13.9k times · Source

I seem to always have problems with this. I have a button outside of the View that calls a function that needs an OrderNumber. I keep getting an error,

ArgumentOutOfRangeException was unhandled by user code

in debug mode, or this one in the browser,

Specified argument was out of the range of valid values.

This is how I'm accessing it:

string sOrderNumber = (Order_DetailsView.Rows[0].Cells[0].Controls[0] as TextBox).Text;
int orderNumber = Int32.Parse(sOrderNumber);

I've also tried ((TextBox)Order_DetailsView.Rows[0].Cells[0].Controls[0]).Text and every combination of indexes in Rows[i].Cells[i].Controls[i] that I could fathom.

Here is the DetailsView:

<asp:DetailsView ID="Order_DetailsView" runat="server" AutoGenerateRows="False">
    <Fields>
        <asp:BoundField DataField="OrderNumber" HeaderText="Order #" />
        <asp:BoundField DataField="GST" HeaderText="GST" DataFormatString="{0:c}" />
        <asp:BoundField DataField="Total" HeaderText="Total" DataFormatString="{0:c}" />
    </Fields>
</asp:DetailsView>

Am I just doing this all wrong? I've looked at every example out there I could find, and my code looks legit from what I can tell. I feel like there must be some simple thing I'm overlooking.

Answer

Vishal Suthar picture Vishal Suthar · Dec 5, 2013

There should be a TemplateField as below:

<asp:DetailsView ID="Order_DetailsView" runat="server" AutoGenerateRows="False">
<Fields>
    <asp:BoundField DataField="OrderNumber" HeaderText="Order #" />
    <asp:BoundField DataField="GST" HeaderText="GST" DataFormatString="{0:c}" />
    <asp:BoundField DataField="Total" HeaderText="Total" DataFormatString="{0:c}" />
    <asp:TemplateField HeaderText="Order Number">                
        <ItemTemplate>
            <asp:TextBox ID="txtOrderNo" runat="server" Text='<%# Bind("OrderNumber") %>'></asp:TextBox>
        </ItemTemplate>                    
    </asp:TemplateField>
</Fields>
</asp:DetailsView>

Then you could access it this way:

string sOrderNumber = ((TextBox)Order_DetailsView.Rows[0].Cells[0].FindControl("txtOrderNo")).Text;

And for the BoundField value you can do this way:

protected void Order_DetailsView_DataBound(object sender, EventArgs e)
{
    string MyOrderNumber = Order_DetailsView.Rows[0].Cells[0].Text;
}