[英]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. 在表单上,我有一个DataGridView,它显示来自SQL数据库和单个表的所有记录。 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.
当我选择一行(OnRowEnter事件)时,我想在textBox中显示相同的数据,这些数据没有绑定到DataSource,但是我不知道如何访问所选的记录及其字段。 I have seen many examples which use SQL statements, but is it the only way?
我已经看到许多使用SQL语句的示例,但这是唯一的方法吗? 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 我正在使用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. 编辑:您刚刚告诉我,您想从数据库中填充2个文本框,然后单击要保存/覆盖的按钮(保存-覆盖)。 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 如果用户在其他文本框中编写文本,并且您想将该文本添加到数据库中的当前文本,那么您只需从数据库中读取文本并将其放入字符串中,就可以在该字符串上从用户中添加字符串并将其保存到数据库中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.