c# - 使用 DataGridView 从另一种形式的 TextBox 中显示数据库信息

标签 c# mysql winforms datagridview

我正在尝试将 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 + "';";

这增加了在创建 frmAdminCommentadmin 对象中检查有效值的负担。

// 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/

相关文章:

c# - 将一个 Windows 窗体设置为另一个 Windows 窗体的 MDI 子窗体(或等同物)

c# - DAL Datamapper 持久化胖对象

mysql - 将 MySQL 数据导入 MS Access 时关系丢失

c# - 我如何告诉设计者我的自定义 winforms 控件具有固定高度?

C# SNMP 代理 - 表示 MIB 中的复杂类型

c# - 模拟具有两个参数的方法时出错

c# - 正则表达式允许拉丁字母和数字数字并且不允许空格

C# 调用非托管 C 驱动程序 (dll)

mysql - mySQL 中 CASE 函数的奇怪工作

python - 尝试了其他方法,还是报错TypeError : 'str' object is not callable