v3z3t4
v3z3t4

Reputation: 65

How to retrieve the value of a colum in GridView

I have a table with the following colums:

FileID | username | filename

I am using a gridview which has two colums:

FileName | Download

In the download column i am having a button called Download which will be used to download files. Now i want to retrieve the fileID or Filename when i click Download button.

I tried this line to get the fileid but it was giving an error:

int FileID = (int)GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;

Error: System.ArgumentOutOfRangeException was unhandled by user code Message=Index was out of range. Must be non-negative and less than the size of the collection.

Here's my aspx page code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="filelist" 
    Width="404px" onrowcommand="GridView1_RowCommand" Height="131px">
    <Columns>
        <asp:BoundField DataField="fileid" HeaderText="fileid" InsertVisible="False" 
            ReadOnly="True" SortExpression="fileid" Visible="False" />
        <asp:BoundField DataField="userid" HeaderText="userid" SortExpression="userid" 
            Visible="False" />
        <asp:BoundField DataField="filename" HeaderText="FileName" 
            SortExpression="filename" />
        <asp:ButtonField HeaderText="Download" Text="Download" CommandName="download"/>
    </Columns>
</asp:GridView>


<asp:SqlDataSource ID="filelist" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
    SelectCommand="SELECT * FROM [FileDetails] WHERE ([userid] = @userid)">
    <SelectParameters>
        <asp:SessionParameter Name="userid" SessionField="userid" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

Is there another way to do this?

Upvotes: 0

Views: 435

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460238

You could use your first BoundField to get the fileid:

GridViewRow row = (GridViewRow)((Control)sender).NamingContainer;
int FileID = int.Parse(row.Cells[0].Text);

Edit: When you're handling the GridView's RowCommand event, the above code does not work since the sender is the GridView instead of the Button. Then you'll find your Button in the GridViewCommandEventArgs.CommandSource:

GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int FileID = int.Parse(row.Cells[0].Text);

Upvotes: 1

Sean Barlow
Sean Barlow

Reputation: 588

Here is how I would access the value in a column inside a datagrid

GridView1.Rows[rowId].Cells[columnId].Value 

Upvotes: 0

Related Questions