简体   繁体   中英

Getting data from selected dataGridView to string

So I'd like to extract a selected data from dataGridView to string variable but I seem to have gone wrong somewhere in the code. How do I go about this? Below is what I'd written but it doesn't seem to be right.

            if ( dataGridView1.SelectedRows.Count != null)
        {
            string itemid = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
            string name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
            string description = dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); 
        }

Try this way. Make sure change the property Multiselect = false and SelectionMode = FullRowSelect to ensure gets only one selection.

SelectedRows.Count is always 0 until you select one

if ( dataGridView1.SelectedRows.Count > 0)
    {
        string itemid = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
        string name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
        string description = dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM