从sql到datagrid视图检索数据

时间:2012-12-05 04:10:13

标签: c#

这段代码不会运行它应该填充datagridview一些数据,但我得到的是检索了多少数据的行,但每个单元格没有值

    public void refDGV()
    {

        con.OpenConnections();
        SqlCommand cmd = new SqlCommand();
        SqlConnection cn = new SqlConnection();
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.Text;
        cn.ConnectionString = con.connections1;
        cmd.CommandText = "Select  dtransdate, ntotal_pass, nincomeday, ndiesel_exp,  nstartkm, nendkm  from ROUTE2 where ccontrol_no = '" +txtCN.Text + "'";
        da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        ds = new DataSet();
        da.Fill(ds, "Data");
        dgroute.DataSource = ds;
        dgroute.DataMember = "Data";
       dgroute.Columns[0].HeaderText = "Date";
       dgroute.Columns[1].HeaderText = "Total Passenger";
       dgroute.Columns[2].HeaderText = "Income Day";
       dgroute.Columns[3].HeaderText = "Diesel (w/ reciept)";
       dgroute.Columns[4].HeaderText = "Start";
       dgroute.Columns[5].HeaderText = "End";




    }

1 个答案:

答案 0 :(得分:3)

你总是可以创建一个DataBase类,如果你需要重构这个Class来传递连接字符串或从.Config文件读取连接字符串,你可以使用它作为模板来开始加上它更清洁 请注意,如果您只是一个建议,我将返回一个DataTable,您可以使用它

public class ClassDataManagement 
{ 
   public DataTable GetData(string sqlcmdString, string connString)
   {
       SqlConnection con = new SqlConnection(connString);
       SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
       SqlDataAdapter da = new SqlDataAdapter(cmd);
       con.Open();
       DataTable dt = new DataTable();
       da.Fill(dt);
       return dt;
   } 
}

如果你想使用DataSet而不是DataTable替换我有DataTable的地方 或者更改方法以返回如下所示的DataSet

   public DataSet GetData(string sqlcmdString, string connString)
   {
       SqlConnection con = new SqlConnection(connString);
       SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
       SqlDataAdapter da = new SqlDataAdapter(cmd);
       con.Open();
       DataSet ds = new DataSet();
       da.Fill(ds);
       return ds;
   }   
返回ds后,你需要像这样绑定它

   dgroute.DataSource = ds;
   dgroute.DataBind();

也为你dgroute Header我认为在将数据分配给ColumnHeader时代码应该是这样的

   dgroute.Rows[0].Column["Heading"] = "Date";
   dgroute.Rows[1].Column["Heading"] = "Total Passenger";
   dgroute.Rows[2].Column["Heading"] = "Income Day";
   dgroute.Rows[3].Column["Heading"] = "Diesel (w/ reciept)";
   dgroute.Rows[4].Column["Heading"] = "Start";
   dgroute.Rows[5].Column["Heading"] = "End";

**重构您的Sql Select语句以允许您为SQL注入设置自己的参数只是一个建设性的建议