【问题标题】:c# gridview not showing result of stored procedure sqlc#gridview不显示存储过程sql的结果
【发布时间】:2016-03-29 17:55:11
【问题描述】:

我正在尝试使用以下代码使用存储过程填充 gridview,但发生的情况是 gridview 没有显示任何内容。

SqlConnection myConnectiona = new SqlConnection("user id=HOME-PC\\HOME;" +
                               "password=password;server=HOME-PC\\SQLEXPRESS;" +
                               "Trusted_Connection=yes;" +
                               "database=tabrem; " +
                               "connection timeout=30");

        SqlCommand pro = new SqlCommand("[dbo].[doctor]", myConnectiona);

        pro.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter da = new SqlDataAdapter(pro);

        DataTable dt = new DataTable();



    try
    {
                myConnectiona.Open();

      da.Fill(dt);
      dataGridView1.DataSource = dt;


    }
    catch (Exception w)
    {
        throw;
    }
    finally
    {
        if (myConnectiona.State == ConnectionState.Open)
            myConnectiona.Close();
    }

【问题讨论】:

  • 可能是您缺少Databind() 命令?
  • C# 太宽泛了,gridview 也是。看起来您正在使用System.Windows.Forms.DataGridView,请更新问题标签以避免“使用DataBind”cmets/posts。
  • 现在正题。你检查过dt.Rows.Count > 0dt.Columns.Count > 0 吗? dataGridView1.AutoPopulateColumns 也是 true?

标签: c# sql-server gridview


【解决方案1】:

设置数据源后:

dataGridView1.DataSource = dt;
dataGridView1.DataBind();

编辑:

在这种情况下,您需要使用 BindingSource:

bindingSource.DataSource = dt;
dataGridView1.DataSource = bindingSource;

https://msdn.microsoft.com/en-us/library/fbk67b6z%28v=vs.110%29.aspx

【讨论】:

  • 这不是asp它是c#所以不需要数据绑定。
  • 是 dataGridView1.AutoGenerateColumns = true 吗?
【解决方案2】:

你需要将数据表绑定到gridview,如下图:

dataGridView1.DataSource = dt;
dataGridView1.Databind();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2021-01-26
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多