How to use a selected value from GridView


I have a GridView which is populated from a select statement. My problem is that i need to grab hold of a column from within the GridView to use in  a select statement. I have a button on the GridView which i want the user to click. and on the click event of that button it needs to grab the ID of the selected row and pass that value to my statement.

Currently the only way i can get it to half work is to hard code the event with an id.

any ideas?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leap29Author Commented:
Sorry neither of these are much help. could either of you explain?
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

IF you can give the snippet what you have tried. we can really help you
leap29Author Commented:
hi , thanks

Below is the code for my gridview. basically i have a button on the gridview that when it is clicked runs an event in the code behind which runs a sql statement to go and fetch a word doc from the sql server based upon the ID of the row that was clicked.

I have tried to use DataKeys but im not entirely sure im going about it in the correct manor.


<asp:GridView ID="GridView1"  runat="server" 
            DataSourceID="SqlDataSource1" DataKeyNames="docid" onselectedindexchanged="GridView1_SelectedIndexChanged1" >
 <asp:TemplateField HeaderText="Show CV" ShowHeader="False">
 <asp:Button runat="server" Text="Show" CommandName="Select" CausesValidation="False" id="Button3"  OnClick="GridView1_SelectedIndexChanged"  />
 protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        System.Data.SqlClient.SqlConnection objConn = new System.Data.SqlClient.SqlConnection();
        objConn.ConnectionString = "Data Source=LOCAL;Password=PASSWORD;User ID=USERNAME;Initial Catalog=NAME OF DB";
        System.Data.SqlClient.SqlCommand objCmd = new System.Data.SqlClient.SqlCommand("NAME OF MY SP", objConn);
        objCmd.CommandType = System.Data.CommandType.StoredProcedure;
       System.Data.SqlClient.SqlParameter test = objCmd.Parameters.Add("@docid",System.Data.SqlDbType.Char);
       test.Direction = System.Data.ParameterDirection.Input;
       test.Value = GridView1.DataKeys[0].Value;
    // GridView1.datakey(Index).(datakeyname value docid).Tostring;
        // Request.QueryString["docid"].ToString(); 
        //string docuid = "@docid";
        //Connection and Parameters
        SqlParameter param = null;
        SqlDataReader reader =
        if (reader.HasRows)
            string doctype = reader["doctype"].ToString();
            string docname = reader["docname"].ToString();
            Response.Buffer = false;
            Response.ContentType = doctype;
                     "attachment; filename=" + docname);
            //Code for streaming the object while writing
            const int ChunkSize = 1024;
            byte[] buffer = new byte[ChunkSize];
            byte[] binary = (reader["document"]) as byte[];
            MemoryStream ms = new MemoryStream(binary);
            int SizeToWrite = ChunkSize;
            for (int i = 0; i < binary.GetUpperBound(0) - 1; i = i + ChunkSize)
                if (!Response.IsClientConnected) return;
                if (i + ChunkSize >= binary.Length)
                    SizeToWrite = binary.Length - i;
                byte[] chunk = new byte[SizeToWrite];
                ms.Read(chunk, 0, SizeToWrite);

Open in new window

Rupesh PCommented:
The ID you meant is the ID gets from the database rt?

See the following line with the CommandArgument property.

<asp:Button runat="server" Text="Show" CommandName="Select" CausesValidation="False" id="Button3"   CommandArgument='<%# Eval("Id") %>'  OnClick="GridView1_SelectedIndexChanged"  />

In the GridView1_SelectedIndexChanged
use like
Int Id = Convert.ToInt32(((Button)sender).CommandArgument);

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
leap29Author Commented:
hi, thanks for this. i getting the following error

The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?)
leap29Author Commented:
sorry actual error is

System.InvalidOperationException: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.