Click here to Skip to main content
14,932,440 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a Datagridview that display some selected columns from database (Name, Data, Content). Can I pass a data into textbox from datagridview cell click using Name as the primary identifier from database?? I have tried any code yet because all the codes i tried only passes from current row in datagridview.

What I have tried:

TextBox1.Text =datagridview1.CurrentRow.Cells["Name"].ToString();

How I design the datagridview

SqlCommand cmd = new SqlCommand("SELECT Name,Data,Content FROM [ContVox]", connect);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
Posted
Updated 4-Mar-21 22:17pm
v2
Comments
BillWoodruff 5-Mar-21 3:38am
   
How do you create the DataGridView Columns ?
Member 13591430 5-Mar-21 3:55am
   
SqlCommand cmd = new SqlCommand("SELECT Name,Data,Content FROM [ContVox]", connect);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);

1 solution

The simplest solution is to bind the textbox to the DGV datasource:
C#
string strConnect = SMDBSupport.SMInstanceStorage.GetInstanceConnectionString("Video list");
using (SqlConnection con = new SqlConnection(strConnect))
    {
    try
        {
        con.Open();
        using (SqlDataAdapter da = new SqlDataAdapter("SELECT Title, ID, Duration, Genre FROM Videos", con))
            {
            DataTable dt = new DataTable();
            da.Fill(dt);
            myDataGridView.DataSource = dt;
            MyTextBox.DataBindings.Add("Text", dt, "Title");
            }
        }
    catch (Exception ex)
        {
        Debug.WriteLine(ex.ToString());
        }
    }
Now when the selection changes, the textbox will be automatically updated.
   
Comments
Member 13591430 5-Mar-21 4:54am
   
Thank you very much, your answers has always being super fine. what if I did not select the column in database. Let say a have columns (Title, ID, Duration, Size) in my database but I am only retrieving (Title, ID, Duration) to the datagridview using the select statement, Can I still Retrieve Column(Size) into a particular textbox after double clicking a datagridview, Ooh the binding textbox to the datagridview will still work, course I haven't try your code, but I know it work out.
OriginalGriff 5-Mar-21 5:06am
   
Retrieve all the columns you are interested in, and set the Name column Visible property to false in the DGV. That way, you keep your data together, instead of spread out over two sources.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900