You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL数据源数据无法显示到手动创建列的DataGridView,求技术支持

问题:手动创建列的DataGridView无法绑定SQL数据显示

已通过「编辑列」功能手动创建DataGridView的列,尝试用以下C#代码从SQL数据源获取数据并绑定,但数据无法正常显示到指定列中,需找出缺失步骤并解决。

界面说明:DataGridView已手动创建多列(如Column1、Column2、Column3),当前无数据填充显示。

原代码

private void button6_Click(object sender, EventArgs e)
{
    string serverName = textBox1.Text;
    string dbName = textBox4.Text;
    string username = textBox2.Text;
    string password = textBox3.Text;
    string tableName = textBox6.Text;

    string connectionString = $"Server={serverName};Database={dbName};User Id={username};Password={password};";

    using (SqlConnection fetchConnection = new SqlConnection(connectionString))
    {
        // connection.Open();
        // Check if the connection is open
        // if (connection == null || connection.State != ConnectionState.Open)
        // {
        //    MessageBox.Show("Please establish a database connection first.", "Connection Required", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //    return;
        // }

        // Fetch data from the SQL data source
        SqlDataAdapter adapter = new SqlDataAdapter($"SELECT sc.name as [Column Name]\r\n\r\nFROM sys.all_columns sc\r\n\r\nJOIN sys.tables st\r\n\r\n ON st.object_id = sc.object_id\r\n\r\nWHERE st.name = '{tableName}' --and schema_id in ('16', '15')\r\n\r\nORDER BY st.name", fetchConnection); //Select YourTable

        DataTable dataTable = new DataTable();
        adapter.Fill(dataTable);

        // If you want to rename a column to "Column2"
        // dataTable.Columns["Column Name"].ColumnName = "Column2";

        // Bind the DataGridView to the retrieved data
        dataGridView1.DataSource = dataTable;
        // dataGridView2.DataSource = dataTable;

        // Replace with your column name
        dataGridView1.Columns["Column3"].DataPropertyName = "ColumnNameP";
    }
}

问题分析

  1. 列映射完全不匹配:SQL查询返回的列别名是[Column Name],但代码中给Column3设置的DataPropertyName是ColumnNameP,两者无关联,导致数据无法绑定到手动列。
  2. 绑定顺序错误:先设置DataSource再修改DataPropertyName,此时数据绑定已完成,修改不会生效。
  3. 自动生成列冲突:DataGridView默认AutoGenerateColumns = true,会自动根据DataTable生成列,导致手动创建的列被覆盖或无法显示数据。
  4. SQL注入风险:直接拼接tableName到SQL语句中,存在严重的SQL注入漏洞。

修复步骤与方案

  1. 关闭自动生成列:在绑定数据前设置dataGridView1.AutoGenerateColumns = false;,确保仅使用手动创建的列。
  2. 调整绑定顺序:先为每个手动列设置正确的DataPropertyName,再绑定DataSource。
  3. 修正列名映射:将手动列的DataPropertyName对应到SQL查询返回的列名(如[Column Name]),或修改SQL查询的别名简化命名(如改为ColumnName)。
  4. 使用参数化查询:替换字符串拼接,用SqlCommand参数化查询避免SQL注入。

完整修复代码

private void button6_Click(object sender, EventArgs e)
{
    string serverName = textBox1.Text;
    string dbName = textBox4.Text;
    string username = textBox2.Text;
    string password = textBox3.Text;
    string tableName = textBox6.Text;

    string connectionString = $"Server={serverName};Database={dbName};User Id={username};Password={password};";

    using (SqlConnection fetchConnection = new SqlConnection(connectionString))
    {
        // 关闭自动生成列,确保使用手动创建的列
        dataGridView1.AutoGenerateColumns = false;

        // 参数化查询,避免SQL注入
        string sqlQuery = @"SELECT sc.name AS ColumnName
                            FROM sys.all_columns sc
                            JOIN sys.tables st ON st.object_id = sc.object_id
                            WHERE st.name = @TableName
                            ORDER BY st.name";

        SqlCommand cmd = new SqlCommand(sqlQuery, fetchConnection);
        cmd.Parameters.AddWithValue("@TableName", tableName);

        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable dataTable = new DataTable();
        adapter.Fill(dataTable);

        // 为手动列设置对应的数据列名
        dataGridView1.Columns["Column3"].DataPropertyName = "ColumnName";
        // 其他手动列需按此格式设置:
        // dataGridView1.Columns["列名"].DataPropertyName = "DataTable中的列名";

        // 最后绑定数据源
        dataGridView1.DataSource = dataTable;
    }
}

额外说明

  • 如果需要保留SQL原有的[Column Name]别名,只需将DataPropertyName设置为"Column Name"(注意空格)。
  • 若手动列数量与DataTable列数量不匹配,需确保每个要显示数据的手动列都正确设置DataPropertyName。

内容的提问来源于stack exchange,提问作者Paul Ang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 19:32:21