Reputation: 113
this code wont run it supposed to fill the datagridview some data but all i got was the rows of how many data was retrieve but no values on each cells
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";
}
Upvotes: 1
Views: 6546
Reputation: 18843
you could always make a DataBase Class and if you need to refactor this Class to pass in Connection String or read Connection string from .Config File you can use this as a template to get started plus it's a lot cleaner Notice that I am returning a DataTable you can use this if you like just a suggestion
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;
}
}
if you want to use DataSet instead of DataTable replace where i have DataTable with or change the method to return a DataSet like this below
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;
}
after returning the ds you will need to bind it like this
dgroute.DataSource = ds;
dgroute.DataBind();
also for you dgroute Header I think the code should read like this when assigning Data to the 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";
**Refactor your Sql Select Statement as well to allow for Parameters you are setting yourself up for SQL Injection just a constructive suggestion
Upvotes: 3