How to use a selected value from GridView

Posted on 2008-11-14
Last Modified: 2012-05-05

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?
Question by:leap29
    LVL 2

    Expert Comment

    LVL 1

    Expert Comment


    Author Comment

    Sorry neither of these are much help. could either of you explain?
    LVL 2

    Expert Comment

    IF you can give the snippet what you have tried. we can really help you

    Author Comment

    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

    LVL 3

    Accepted Solution

    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);


    Author Comment

    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?)

    Author Comment

    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.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Training Course: Java/J2EE and SOA

    This course will cover both core and advanced Java concepts like Database connectivity, Threads, Exception Handling, Collections, JSP, Servlets, XMLHandling, and more. You'll also learn various Java frameworks like Hibernate and Spring.

    For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
    User art_snob ( encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
    This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA.…
    This video discusses moving either the default database or any database to a new volume.

    758 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now