【问题标题】:How do I connect gridview to sql using C# in asp.net?如何在 asp.net 中使用 C# 将 gridview 连接到 sql?
【发布时间】:2012-01-30 22:05:46
【问题描述】:

我知道如何连接、打开、阅读和关闭,如下所示。我也有很棒的教程如何添加更新/删除等。

我可以使用 asp.net 控件将 dataTable 连接到 sql,但我想学习如何从 C# 操作它。

MasterCust 是我的 gridview 表名。如何连接到它?

protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection Conn = new SqlConnection("Data Source=aserver;Initial Catalog=KennyCust;Persist Security Info=True;user id=sa;pwd=qwerty01");
        SqlDataReader rdr = null;
        string commandString = "SELECT * FROM MainDB";

        try
        {
            Conn.Open();
            SqlCommand Cmd = new SqlCommand(commandString, Conn);

            rdr = Cmd.ExecuteReader();

            while (rdr.Read())
            {
                Console.WriteLine(rdr[0]);
            }
        }
        finally
        {
            if (rdr != null)
            {
                rdr.Close();
            }
            if (Conn != null)
            {
                Conn.Close();
            }
        }
        //MasterCust.
        //MasterCust.DataSource = commandString;
        //MasterCust.DataBind();
    }

编辑:此代码有效

            try
        {
            Conn.Open();
            SqlCommand Cmd = new SqlCommand(commandString, Conn);
            SqlDataAdapter sdp = new SqlDataAdapter(Cmd);
            DataSet ds = new DataSet();

            sdp.Fill(ds);
            //rdr = Cmd.ExecuteReader();
            MasterCust.DataSource = ds.Tables[0];
            MasterCust.DataBind();


            }

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    设置 GridView 的 Datasource 属性并调用 DataBind 方法。

    此代码将起作用。 (测试)

     SqlConnection Conn = new SqlConnection("Data Source=Localhost\\SQLEXPRESS;Initial Catalog=Flash2;Integrated Security=True;");
     SqlDataReader rdr = null;
     string commandString = "SELECT * FROM USER_MASTER";
    
     try
     {
            Conn.Open();
            SqlCommand Cmd = new SqlCommand(commandString, Conn);
            rdr = Cmd.ExecuteReader();
    
            MasterCustView.DataSource = rdr;
            MasterCustView.DataBind();
     }
     catch (Exception ex)
     {
          // Log error
     }
     finally
     {
         if (rdr != null)
         {
             rdr.Close();
         }
         if (Conn != null)
         {
             Conn.Close();
         }
      }
    

    【讨论】:

    • myReader 来自哪里?
    • 在没有捕获的情况下出现错误是一个不好的迹象吗?如果我在其中添加 catch 可以正常工作,但加载速度真的很慢......这可能是由于编码错误吗?
    • 该代码应该可以工作。我测试了它。对于缓慢,您在谈论多少数据? 100 万条记录?表中有正确的索引吗?
    猜你喜欢
    • 2013-03-10
    • 2011-07-30
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2018-04-15
    相关资源
    最近更新 更多