简体   繁体   中英

c# how to access data fields of the selected in DataGridView database record

I'm new to the database programming, so I have probably very simple question.

On the form I have a DataGridView which shows all records from the SQL database, from single table. When I select a line (OnRowEnter event), I would like to display the same data in the textBoxes, which are not binded to the DataSource, but I do not know how to access the selected record and its fields. I have seen many examples which use SQL statements, but is it the only way? Or is there a simpler method. I thought I should be able to access the current record and its fields almost directly? Is it possible?

I'm using Visual Studio Community 2013

Thx in advance for your help.

    private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
    {
        string asd = dataGridView1.Rows[e.RowIndex].Cells["NameOfColumn"].Value.ToString();
    }

You can access any column of any row by this line.

EDIT: You just told me you want to populate 2 textboxes from database and on buttons(save - overwrite) you want to save/overwrite it. So why you do not populate it from database

using (FbConnection con = new FbConnection(connectionString))
{
    con.Open();
    using (FbCommand cmd = new FbCommand("SELECT TEXT1, TEXT2 FROM TABLE WHERE CONDITION", con))
    {
        FbDataReader dr = cmd.ExecuteReader();
        if(dr.Read())
        {
            textBox1.Text = dr[0].ToString();
            textBox2.Text = dr[1].ToString();
        }
    }
    con.close();
}

and then after user press save you just take whole text and update database

using (FbConnection con = new FbConnection(connectionString))
{
    con.Open();
    using (FbCommand cmd = new FbCoimmand("UPDATE TABLE SET TEXT1 = @Text1, TEXT2 = @Text2 WHERE CONDITION))
    {
        cmd.Parameters.AddWithValue("@Text1", textBox1.Text);
        cmd.Parameters.AddWithValue("@Text2", textBox2.Text);

        cmd.ExecuteNonQuery();
    }
    con.Close();
}

if user is writing text in some other textbox and you want to add that text to current text in database so you just read text from database and put it in string, on that string you add string from user and save like that to database

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