【问题标题】:get data from database and display it in gridview (asp.net)从数据库中获取数据并在gridview(asp.net)中显示
【发布时间】:2015-05-04 13:36:38
【问题描述】:

我有一个数据库(SQL 服务器)并将其添加到我的网页项目中,但问题是我无法在 gridview 中显示数据。

这是我的代码:

string query;
SqlCommand SqlCommand;
SqlDataReader reader;
int sindex=DropDownList1.SelectedIndex+1;
int hindex =DropDownList3.SelectedIndex+1;
SqlDataAdapter adapter = new SqlDataAdapter();
//Open the connection to db
conn.Open();                
query = string.Format("select * from table where clumn='"+s+"' ", s);
SqlCommand = new SqlCommand(query, conn);
adapter.SelectCommand = new SqlCommand(query, conn);              
reader = SqlCommand.ExecuteReader();               
GridView2.DataSource = reader;
GridView2.DataBind();

【问题讨论】:

    标签: c# asp.net sql-server gridview webforms


    【解决方案1】:

    改变这个

    query = string.Format("select * from table where clumn='"+s+"' ", s);
    

    到这里

    query = string.Format("select * from table where clumn='{0}' ", s);
    

    【讨论】:

    • 其实用参数就好了。
    【解决方案2】:

    使用 SqlParameters 而不是像现在这样操作字符串。
    另外,请使用using 语句正确处理对象。
    不要使用select *,因为它会影响性能,只选择需要的列。
    这是您的代码示例,已修改:

    using (SqlConnection conn = new SqlConnection(yourConnectionString))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        command.CommandType = CommandType.Text;
        command.CommandText = "select column, column2 from table where column=@column";
    
        command.Parameters.Add(new SqlParameter("column", SqlDbType.VarChar, 50));
        command.Parameters["column"].Value = yourColumnValue;
    
        conn.Open();
    
        using (SqlDataReader sdr = sco.ExecuteReader())
        {
            GridView2.DataSource = sdr;
            GridView2.DataBind();
        }
    }  
    

    【讨论】:

      【解决方案3】:

      更好地使用SqlDatadapter:

        DataTable dt = new DataTable();
       ...
      using (SqlDataAdapter a = new SqlDataAdapter( new SqlCommand(query, conn)))
                        {
                            GridView2.DataSource =a.Fill(dt).AsDataView();
                        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-27
        • 2018-11-06
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多