我正在尝试将 MySQL 数据库中的信息(用户评论)显示到另一种形式的文本框中。我正在使用 datagridview 来选择 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);
}
编辑:我已经更新了我的代码。即使我选择了另一行,代码也只会检索 datagridview 中第一行的注释。
最佳答案
您的问题可能是源 (admin.gridClients
) GridView 上没有 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。
关于c# - 使用 DataGridView 从另一种形式的 TextBox 中显示数据库信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27589365/