使用 DataGridView 从另一个窗体在文本框中显示数据库信息
本文关键字:显示 数据库 信息 文本 DataGridView 另一个 窗体 使用 | 更新日期: 2023-09-27 18:34:45
我正在尝试将MySQL数据库中的信息(用户评论(以另一种形式显示到文本框中。我正在使用数据网格视图来选择 UID 以识别注释适用于哪个用户。我的代码在注释表单的加载事件中,就像这样...
try
{
// Check if a row is selected.
string cRow = admin.gridClients.CurrentRow.Cells[0].Value.ToString();
string Query = "SELECT Admin_Com FROM cpr_clients WHERE Client_ID='" + cRow + "';";
MySqlConnection myConn = new MySqlConnection(strConnect);
MySqlCommand myCmd = new MySqlCommand(Query, myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = myCmd.ExecuteReader();
while (myReader.Read())
{
txtAdminCom.Text = myReader["Admin_Com"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
编辑:我已经更新了我的代码。该代码仅检索数据网格视图中第一行的注释,即使我选择了另一行也是如此。
您的问题可能是源 (admin.gridClients
( 网格视图上没有CurrentRow
。这将导致尝试访问.Cells
抛出您收到的错误,因为CurrentRow == null
.
由于您只需要此值来标识frmAdminComment
中的 Id,因此读取源表单中的值,然后将其传递给 frmAdminComment
的构造函数:
private string _id;
public frmAdminComment(string id)
{
// Initialization code you already have.
// Set the Id for this instance.
_id = id;
}
现在在加载方法中引用_id
变量:
string Query = "SELECT Admin_Com FROM cpr_clients WHERE Client_ID='" + _id + "';";
这会将检查有效值的负担放在正在创建frmAdminComment
的admin
对象中。
// In the "admin" object.
if (gridClients.CurrentRow == null)
{
MessageBox.Show("No CurrentRow is set in the source grid.");
return;
}
else
{
// CurrentRow is set - safe to reference it.
var adminComment = new frmAdminComment(gridClients.CurrentRow.Cells[0].Value.ToString());
adminComment.Show();
}
您可能需要考虑改用 SelectedRows
属性。它将像这样工作:
// Check if a row is selected.
// In the "admin" object.
if (gridClients.SelectedRows.Length == 0)
{
MessageBox.Show("No rows selected in the source grid.");
}
else
{
// CurrentRow is set - safe to reference it.
var adminComment = new frmAdminComment(gridClients.SelectedRows[0].Cells[0].Value.ToString());
adminComment.Show();
}
请注意,如果使用SelectedRows
则可能需要将 gridClients
上的属性设置为一次只允许选择一行,并将选择模式设置为 FullRowSelect。