使用DataGridView从另一个表单在TextBox中显示数据库信息
我试图将我的MySQL数据库中的信息(用户评论)显示为另一种forms的文本框。 我正在使用datagridview来选择UID以识别注释所针对的用户。 我的代码在Comment表单的load事件中,就像这样……
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
)网格视图上没有CurrentRow
。 这将导致尝试访问.Cells
抛出你得到的错误,因为CurrentRow == null
。
由于您只需要此值来标识frmAdminComment
的Id,请读取源表单中的值,然后将其传递给frmAdminComment
的构造frmAdminComment
:
private string _id; public frmAdminComment(string id) { // Initialization code you already have. // Set the Id for this instance. _id = id; }
现在引用load方法中的_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的情况下,一次只能选择一行。