如何从数据库到网格视图获取单行数据 [英] how to get singel row data from database to gridview

查看:61
本文介绍了如何从数据库到网格视图获取单行数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public DataSet getgridforConsignor(string Consigner)
    {
         string sql = "";
          string Constr = ConfigurationManager.ConnectionStrings["YET_DatabaseConnectionString"].ConnectionString.ToString();
             SqlConnection conn = new SqlConnection(Constr);
             DataTable dt = new DataTable();
             DataSet ds = new DataSet();
         try
        {
            
             conn.Open();
            // string DDConsignor = DDCOnsignee.Text;
             sql = "select Dt,CNo,BiltyFrm,BiltyTo,NoOfPackages,InvoiceNo,ChargedWt,RatePerKg,Freight,Total,PaidBy from Bilty where Consigner="+Consigner ;
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader rd = cmd.ExecuteReader();
            
            // SqlDataAdapter da = new SqlDataAdapter(sql, conn);
             //da.Fill(ds);
             //ds.Tables.Add(sql );
             dt.Load(rd);
             //ds.Tables.Add(dt);
             GridView1.DataSource = dt;
             GridView1.DataBind();

         }
         catch (Exception ex)
         {
             MessageBox.Show("ERR in getgridforConsignor(string Consignor)" + ex.Message  );
         }
         finally 
         {
             conn.Close();
         }
         return ds;
    }

推荐答案

您的select语句需要返回单个项目,或者需要在将DataView分配为DataSource之前对其进行过滤. >
您的代码也有几处错误.

您应该学习使用using语句.这将使您的代码更易于阅读和维护,并确保正确处置对象.

Your select statement needs to return a single item, or you need to filter the DataView before assigning it as the DataSource.

There are several things wrong with your code also.

You should learn to use the using statement. It will make your code easier to read and maintain, and ensure objects are properly disposed of.

using(SqlConnection conn = new SqlConnection(Constr))
{
   using(SqlCommand cmd = new SqlCommand(sql, conn))
   {

   }
}



切勿接受未经验证的输入到sql语句中. SQL注入攻击已经被写了很多遍了.



NEVER accept unvalidated input into a sql statement. SQL Injection attacks have been written about many, many times.


这篇关于如何从数据库到网格视图获取单行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆