How to use a selected value from GridView

Hi,

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?
leap29Asked:
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.

YogeshupCommented:
0
leap29Author Commented:
Sorry neither of these are much help. could either of you explain?
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

pr_rCommented:
IF you can give the snippet what you have tried. we can really help you
0
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.

thanks

<asp:GridView ID="GridView1"  runat="server" 
            DataSourceID="SqlDataSource1" DataKeyNames="docid" onselectedindexchanged="GridView1_SelectedIndexChanged1" >
 <Columns>
 <asp:TemplateField HeaderText="Show CV" ShowHeader="False">
<ItemTemplate>
 <asp:Button runat="server" Text="Show" CommandName="Select" CausesValidation="False" id="Button3"  OnClick="GridView1_SelectedIndexChanged"  />
</ItemTemplate>                      
</asp:TemplateField>           
</Columns>
 </asp:GridView>
 
 
 
 
 
 
 
 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";
        objConn.Open();
 
        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 =
          objCmd.ExecuteReader(CommandBehavior.CloseConnection);
        if (reader.HasRows)
        {
            reader.Read();
            //
            string doctype = reader["doctype"].ToString();
            string docname = reader["docname"].ToString();
   
            //
            Response.Buffer = false;
            Response.ClearHeaders();
            Response.ContentType = doctype;
            Response.AddHeader("Content-Disposition",
                     "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);
                Response.BinaryWrite(chunk);
                Response.Flush();
            }
            Response.Close();
 
        }
    }

Open in new window

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

0

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?)
0
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.
0
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
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.