Click here to Skip to main content
15,892,965 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, please help me on getting datagridview multiple selection to textbox with comma, if i select multiple row i am getting only one rows column to textbox, below is code which i have done so far..

<
C#
private void btnUpdate_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow drv in dataGridView1.SelectedRows)
            {
                textBox1.Text = "";
                bool val = true;
                if (dataGridView1.SelectedRows != null)
                {
                    if (!firstvalue)
                    {
                        textBox1.Text = ",";
                    }
                    textBox1.Text = textBox1.Text + dataGridView1.SelectedCells[1].Value.ToString();
                    val = false;
                }
            }
        }
Posted

You are resetting the text instead of appending the comma in the if loop. Your code in the if block should be.

C#
if (!firstvalue)
{
     textBox1.Text += ",";
}


UPDATE SM:
Try:
C#
if (!firstvalue)
{
   textBox1.Text += "," + dataGridView1.SelectedCells[1].Value.ToString();
}


Update #2 Tarak:
Another problem is you are resetting the textBox1.Text = "" for each of the row. You have to move it out of the foreach. Also you need to use the drv and get the value from that.

C#
private void btnUpdate_Click(object sender, EventArgs e)
{
   if (dataGridView1.SelectedRows != null)
   {
       textBox1.Text = "";
       bool firstvalue = true;
       foreach (DataGridViewRow drv in dataGridView1.SelectedRows)
       {      
          if (!firstvalue)
          {
             textBox1.Text += ",";
          }
          textBox1.Text += drv.Cells[1].Value.ToString();
          firstvalue = false;
      }
   }
}
 
Share this answer
 
v5
Comments
jaipe 23-Apr-11 0:39am    
Hi Tarakeshwar, i am getting only one value to textbox even by trying your advice, kindly advice on the same pls
Sandeep Mewara 23-Apr-11 0:43am    
Try the updated answer.

BTW, a simple DEBUGGER use can tell you what is going wrong and where. Try it!
Tarakeshwar Reddy 23-Apr-11 0:48am    
I agree, a simple debug would have shown what the problem was.
Tarakeshwar Reddy 23-Apr-11 0:52am    
Take a look at the updated solution. You were also resetting the textBox1.Text value in the foreach and that was causing you to see only one value.
Sandeep Mewara 23-Apr-11 0:41am    
My 5!
Proposed as answer.
C#
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
        //Column Num represents col names
    MessageBox.Show(row.Cells[1].Value.ToString());
//////////////The 1 Represent the grid column you want the data from

}

By stylesmylez
 
Share this answer
 

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



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