Datagridview items are showing up empty? - c#

I was hoping you could help me with this little problem. I did this to add all my users accounts details to a datagridview and now the colums are all empty?
public DataTable GetResultsTable(string Username)
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'");
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
DataRow dr = table.NewRow();
dr["Username"] = "" + row["username"] + "";
dr["Motto"] = "" + row["motto"] + "";
dr["Email"] = "" + row["mail"] + "";
dr["Homeroom"] = "" + row["home_room"] + "";
dr["Health"] = "" + row["health"] + "";
dr["Energy"] = "" + row["energy"] + "";
dr["Age"] = "" + row["age"] + "";
table.Rows.Add(dr);
return table;
}
}
SqlDatabaseManager.Initialize();
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows)
{
dataGridView1.DataSource = GetResultsTable((string)row2["username"]);
}
my execute query is
public DataRow ExecuteQueryRow(string CommandText)
{
DataTable DataTable = ExecuteQueryTable(CommandText);
return DataTable.Rows.Count > 0 ? DataTable.Rows[0] : null;
}

public DataRow GetResultsTable(string Username)
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'");
DataRow dr = new DataRow;
dr.Columns.Add("Username".ToString());
dr.Columns.Add("Motto".ToString());
dr.Columns.Add("Email".ToString());
dr.Columns.Add("Homeroom".ToString());
dr.Columns.Add("Health".ToString());
dr.Columns.Add("Energy".ToString());
dr.Columns.Add("Age".ToString());
dr["Username"] = "" + row["username"] + "";
dr["Motto"] = "" + row["motto"] + "";
dr["Email"] = "" + row["mail"] + "";
dr["Homeroom"] = "" + row["home_room"] + "";
dr["Health"] = "" + row["health"] + "";
dr["Energy"] = "" + row["energy"] + "";
dr["Age"] = "" + row["age"] + "";
return dr;
}
}
SqlDatabaseManager.Initialize();
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows)
{
table .Rows.Add( GetResultsTable((string)row2["username"]));
}
DataGridView.DataSourse=table ;

Related

make line break in string array output in c#

how to make line break between words in this following code ? i want to show each output have line break like this so that it can be seen properly. this is my code and output that i want :
try
{
//DataTable dtTemp = (DataTable)ViewState["Information"];
DataTable dtDistinctRecords = dtTemp.DefaultView.ToTable(true, "prod_line");
DataTable dtStudentName = dtTemp.DefaultView.ToTable(true, "request_date");
DataTable a = new DataTable();
DataTable dtStudent = new DataTable();
dtStudent.Columns.Add("request_date");
foreach (DataRow rows in dtDistinctRecords.Rows)
{
dtStudent.Columns.Add(rows["prod_line"].ToString());
}
foreach (DataRow row in dtStudentName.Rows)
{
DataRow dr = dtStudent.NewRow();
dr["request_date"] = row["request_date"];
DataView dv = new DataView(dtTemp);
dv.RowFilter = "request_date='" + row["request_date"] + "'";
DataTable dtStudentdtl = dv.ToTable();
for (int i = 0; i < dtStudentdtl.Rows.Count; i++)
{
string colValue = dtStudentdtl.Rows[i]["jo_no"].ToString();
string colValue2 = dtStudentdtl.Rows[i]["qty"].ToString();
string colValue3 = dtStudentdtl.Rows[i]["need_by_date"].ToString();
string colValue4 = dtStudentdtl.Rows[i]["process_id"].ToString();
dr[dtStudentdtl.Rows[i]["prod_line"].ToString()] = "Job Order: " + colValue + " Quantity: " + colValue2 + " Need by Date: " + colValue3 + " Status: " + colValue4;
var joinedWords = string.Join(" ", dtStudent);
}
dtStudent.Rows.InsertAt(dr, dtStudent.Rows.Count);
}
GridView1.CellPadding = 10;
GridView1.DataSource = dtStudent;
GridView1.DataBind();
GridView_Row_Merger(GridView1);
con.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
link output that i want
Here's the first result from google for you, adding line break,
or for short \r\n
I made some changes in your for loop to make a sample code snippet:
string colValue = "job order: 124"+System.Environment.NewLine+System.Environment.NewLine;
string colValue2 = "Quantity: 100" + System.Environment.NewLine + System.Environment.NewLine;
string colValue3 = "Need by Date:2/5/2017" + System.Environment.NewLine + System.Environment.NewLine;
string colValue4 = "Status: Pending"+System.Environment.NewLine;
string finalString = colValue + colValue2 + colValue3 + colValue4;
and in front end i am getting following output:
Hope it will work for you.

How to get header name in autogenerated GridView

How to get the header name in an autogenerated GridView in a Button click event.header column must not be same..all the time..
So depending upon the column header we have to process further. Please help to find the column header.
We are finding the rowindex by below code
var rowIndex = ((GridViewRow)((Control)sender).NamingContainer).RowIndex;
like this. So how to find the column index of a GridView when a link button is clicked inside the GridView?
'
string dt1 = txtFromDate.Text;
string d1, d5 = "", d3 = "", d4 = "", date, d6, service_Date;
if (dt1 != "")
{
d1 = dt1;
if (d1.Contains("."))
{
string[] word = d1.Split('.');
d5 = word[0];
d3 = word[1];
d4 = word[2];
}
else if (d1.Contains("-"))
{
string[] word = d1.Split('-');
d5 = word[0];
d3 = word[1];
d4 = word[2];
}
else if (d1.Contains("/"))
{
string[] word = d1.Split('/');
d5 = word[0];
d3 = word[1];
d4 = word[2];
}
date = d4 + "/" + d3 + "/" + d5;
service_Date = d5 + "-" + d3 + "-" + d4;
}
else
{
date = "";
service_Date = "";
}
string dt2 = txtToDate.Text;
string t1, t5 = "", t3 = "", t4 = "", d2, t6, serv;
if (dt1 != "")
{
t1 = dt2;
if (t1.Contains("."))
{
string[] word = t1.Split('.');
t5 = word[0];
t3 = word[1];
t4 = word[2];
}
else if (t1.Contains("-"))
{
string[] word = t1.Split('-');
t5 = word[0];
t3 = word[1];
t4 = word[2];
}
else if (t1.Contains("/"))
{
string[] word = t1.Split('/');
t5 = word[0];
t3 = word[1];
t4 = word[2];
}
d2 = t4 + "/" + t3 + "/" + t5;
serv = t5 + "-" + t3 + "-" + t4;
//d5 = d3 + "/" + d6 + "/" + d4 ;
}
else
{
d2 = "";
serv = "";
}
dttest.Columns.Add("MACHINENAME_DATE");
ArrayList Array_machine = new ArrayList();
using (con = new SqlConnection(con_str))
{
con.Open();
string qry;
qry = "select distinct mname from tb_reqmach where fromdate>='" + date + "' and todate<='" + d2 + "' and mcfact='" + drpfact.Text + "' group by mname ";
cmd = new SqlCommand(qry, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
Array_machine.Add(dr["mname"].ToString().Trim());
//dttest.Rows.Add();
dttest.Rows.Add(dr["mname"].ToString().Trim());
}
con.Close();
}
ArrayList Array_L = new ArrayList();
DateTime startDate = Convert.ToDateTime(date);
Array_L.Add(startDate.ToString("MM-dd-yyyy"));
dttest.Columns.Add(startDate.ToShortDateString());
DateTime endDate = Convert.ToDateTime(d2);
while (startDate < endDate)
{
startDate = startDate.AddDays(1);
Array_L.Add(startDate.ToString("MM-dd-yyyy"));
dttest.Columns.Add(startDate.ToShortDateString());
}
DataTable dt = new DataTable();
int m = 0;
for (int j = 0; j < Array_L.Count; j++)
{
int avail = 0;
int planned = 0;
int req = 0;
for (int d = 0; d < Array_machine.Count; d++)
{
//dttest.Columns.Add();
// dttest.Columns.Add();
// xlworksheet.Cells[4 + d, 1] = Array_machine[d];
// dttest.Rows.Add();
string machine_name = Array_machine[d].ToString();
string Date = Array_L[j].ToString();
// xlworksheet.Cells[3, m + 2] = Date;
//DataColumn[] keyColumns = new DataColumn[1];
//keyColumns[0] = dttest.Columns["MACHINENAME/DATE"];
//dttest.PrimaryKey = keyColumns;
//if (dttest.Rows.Contains(machine_name))
//{
//}
//else
//{
//dttest.Rows.Add(machine_name);
//}
// dttest.Rows[d][1] = Array_machine[d];
// [xlworksheet].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
// xlworksheet.Range["A3", m + 2].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#99CCFF");
// dt.Columns.Add(machine_name);
using (con = new SqlConnection(con_str))
{
con.Open();
string qry1;
//qry = "select distinct mname from tb_reqmach where mcfact='" + drpfact.Text + "' group by mname ";
qry1 = "select count(mcdesp) as mcdesp from machine where mcdesp='" + Array_machine[d].ToString().Trim() + "' and mcfact='" + drpfact.Text + "' ";
cmd = new SqlCommand(qry1, con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
// xlworksheet.Cells[dtcount + 1, m + 7] = dr["mcdesp"].ToString().Trim();
avail = Convert.ToInt32(dr["mcdesp"].ToString().Trim());
}
con.Close();
con.Open();
string qry;
qry = "SELECT sum(rmachine) as mname FROM tb_reqmach WHERE '" + Array_L[j].ToString() + "' BETWEEN fromdate AND todate and mname='" + Array_machine[d].ToString().Trim() + "' and mcfact='" + drpfact.Text + "'";
cmd = new SqlCommand(qry, con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
// dttest.Rows.Add();
//xlworksheet.Columns[i].ColumnWidth = 18;
// xlworksheet.Cells[d + 4, 2 + m] = dr["mname"].ToString().Trim();
dttest.Rows[d][j + 1] = dr["mname"].ToString().Trim();
if (dr["mname"].ToString().Trim() != "")
{
planned = Convert.ToInt32(dr["mname"].ToString().Trim());
req = avail - planned;
int rows = d + 4;
int cols = 2 + m;
// string rowA = FindResA(rows);
// string colB = FindResB(cols);
if (req < 0)
{
// xlworksheet.Range[colB + rows, colB + rows].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#ff0000");
}
else
{
// xlworksheet.Range[colB + rows, colB + rows].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#008000");
}
}
// dttest.Rows[d][m+1] = dr["mname"].ToString().Trim();
// xlworksheet.Columns.AutoFit();
// gvtest.HeaderRow.Cells(d).Text = dr["mname"].ToString().Trim();
//dt.Rows.Add();
// dt.Rows[d][machine_name] = dr["mname"].ToString().Trim();
}
con.Close();
}
}
m++;
// gvtest.DataSource = dt;
// gvtest.DataBind();
//ID = (i + 1).ToString();
// string machine_name = Array_machine[j].ToString();
// xlworksheet.Cells[4 + i, 1] = ID;
// xlworksheet.Cells[4 + i, 2] = machine_name;
// xlworksheet.Cells[3, m + 2] = machine_name;
//
}
Session["dttest"] = dttest;
GridView4.DataSource = dttest;
GridView4.DataBind();
for (int j = 0; j < Array_L.Count; j++)
{
int avail = 0;
int planned = 0;
int req = 0;
for (int d = 0; d < Array_machine.Count; d++)
{
//dttest.Columns.Add();
// dttest.Columns.Add();
// xlworksheet.Cells[4 + d, 1] = Array_machine[d];
// dttest.Rows.Add();
string machine_name = Array_machine[d].ToString();
string Date = Array_L[j].ToString();
// xlworksheet.Cells[3, m + 2] = Date;
//DataColumn[] keyColumns = new DataColumn[1];
//keyColumns[0] = dttest.Columns["MACHINENAME/DATE"];
//dttest.PrimaryKey = keyColumns;
//if (dttest.Rows.Contains(machine_name))
//{
//}
//else
//{
//dttest.Rows.Add(machine_name);
//}
// dttest.Rows[d][1] = Array_machine[d];
// [xlworksheet].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
// xlworksheet.Range["A3", m + 2].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#99CCFF");
// dt.Columns.Add(machine_name);
using (con = new SqlConnection(con_str))
{
con.Open();
string qry1;
//qry = "select distinct mname from tb_reqmach where mcfact='" + drpfact.Text + "' group by mname ";
qry1 = "select count(mcdesp) as mcdesp from machine where mcdesp='" + Array_machine[d].ToString().Trim() + "' and mcfact='" + drpfact.Text + "' ";
cmd = new SqlCommand(qry1, con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
// xlworksheet.Cells[dtcount + 1, m + 7] = dr["mcdesp"].ToString().Trim();
avail = Convert.ToInt32(dr["mcdesp"].ToString().Trim());
}
con.Close();
con.Open();
string qry;
qry = "SELECT sum(rmachine) as mname FROM tb_reqmach WHERE '" + Array_L[j].ToString() + "' BETWEEN fromdate AND todate and mname='" + Array_machine[d].ToString().Trim() + "' and mcfact='" + drpfact.Text + "'";
cmd = new SqlCommand(qry, con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
// dttest.Rows.Add();
//xlworksheet.Columns[i].ColumnWidth = 18;
// xlworksheet.Cells[d + 4, 2 + m] = dr["mname"].ToString().Trim();
// dttest.Rows[d][j + 1] = dr["mname"].ToString().Trim();
if (dr["mname"].ToString().Trim() != "")
{
planned = Convert.ToInt32(dr["mname"].ToString().Trim());
req = avail - planned;
int rows = d + 4;
int cols = 2 + m;
// string rowA = FindResA(rows);
// string colB = FindResB(cols);
if (req < 0)
{
GridView4.Rows[d].Cells[j + 1].BackColor = Color.Red;
}
else
{
}
}
}
con.Close();
}
}
m++;
}
foreach (GridViewRow gr in GridView4.Rows)
{
// LinkButton hp = new LinkButton();
for (int k = 1; k < dttest.Columns.Count; k++)
{
LinkButton hp = new LinkButton();
if (gr.Cells[k].Text != "")
{
hp.Text = gr.Cells[k].Text;
//defsur_Click(sender, e);
//GridViewRow gvr = e.Row;
//var rowIndex = ((GridViewRow)((Control)sender).NamingContainer).RowIndex;
//Label username = (Label)GridView3.Rows[rowIndex].FindControl("machinename");
//mcname = username.Text;
// hp.Attributes.Add("onclick", "Gridview4_linkclick");
hp.Click += new EventHandler(Gridview4_linkclick);
// hp.NavigateUrl = "~/Default.aspx?name=" + hp.Text;
gr.Cells[k].Controls.Add(hp);
}
}
}
GridView4.Columns[0].Visible = false;'
You can use this snippet. It loops all the cells in the row the clicked button is in and tries to find the correct column.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//get the control that fired the method
Control control = e.CommandSource as Control;
//get the row containing the control
GridViewRow gvr = control.NamingContainer as GridViewRow;
//get the row number
int rowNumber = gvr.RowIndex;
//declare the column variable
int columnNumber = -1;
//loop all the columns in the gridview
for (int i = 0; i < GridView1.Columns.Count; i++)
{
//try to find the button that was clicked in each individual cell
Button button = GridView1.Rows[rowNumber].Cells[i].FindControl(control.ID) as Button;
//if the button is found set the column number
if (button != null)
{
columnNumber = i;
}
}
//get the column name
Label1.Text = GridView1.HeaderRow.Cells[columnNumber].Text;
}
GridView example
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

how to add the value in a variable to a datatable

I have a DataTable called datatablebuy. I need to insert a value called avg to the DataTable and display it in the girdview. I have obtained the value for datatablebuy from database called transac. How can I add the value in the variable "avg" to the datatablebuy. I am using C# for coding, The code looks as follows :
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
var sql = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Sell' and scriptname = '" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var sqll = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Buy' and scriptname ='" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var da = new SqlDataAdapter(sqll, conn);
var dataTablebuy = new DataTable();
da.Fill(dataTablebuy);
var dataAdapter = new SqlDataAdapter(sql, conn);
var dataTablesell = new DataTable();
dataAdapter.Fill(dataTablesell);
foreach (DataRow row in dataTablesell.Rows)
{
foreach (DataRow rw in dataTablebuy.Rows)
{
if (double.Parse(rw["Quantity"].ToString()) > double.Parse(row["Quantity"].ToString()))
{
rw["Quantity"] = double.Parse(rw["Quantity"].ToString()) - double.Parse(row["Quantity"].ToString());
row["Quantity"] = 0;
}
else
{
row["Quantity"] = double.Parse(row["Quantity"].ToString()) - double.Parse(rw["Quantity"].ToString());
rw["Quantity"] = 0;
}
}
}
float denom = 0;
float numer = 0;
float avg = 0;
foreach (DataRow rw in dataTablebuy.Rows)
{
denom = denom + int.Parse(rw["Quantity"].ToString());
numer = numer + (int.Parse(rw["Quantity"].ToString()) * int.Parse(rw["price"].ToString()));
avg = numer / denom;
}
GridView1.DataSource = dataTablebuy;
GridView1.DataBind();
ViewState["dataTablebuy"] = dataTablebuy;
GridView1.Visible = true;
Response.Write("average " +avg.ToString());
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
Response.Write("error" + sqlEx.ToString());
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
after
dataAdapter.Fill(dataTablesell);
you have to add column to DataTable like this
dataTablesell.Columns.Add("avg",typeof(decimal));
then inside
foreach (DataRow row in dataTablesell.Rows)
{
foreach (DataRow rw in dataTablebuy.Rows)
{
row["avg"]=0;
//set your avg value here
}
}
dataTablebuy.Columns.Add("avg", typeof(int));
foreach (DataRow rw in dataTablebuy.Rows)
{
rw["avg"] = //Pleaase assign average value here
}
i hope this will work.
First add avg column into your dataTablebuy DataTable then assign your avg variable to avg column.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
var sql = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Sell' and scriptname = '" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var sqll = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Buy' and scriptname ='" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var da = new SqlDataAdapter(sqll, conn);
var dataTablebuy = new DataTable();
da.Fill(dataTablebuy);
dataTableBuy.Columns.Add("Avg",typeof(float));
var dataAdapter = new SqlDataAdapter(sql, conn);
var dataTablesell = new DataTable();
dataAdapter.Fill(dataTablesell);
foreach (DataRow row in dataTablesell.Rows)
{
foreach (DataRow rw in dataTablebuy.Rows)
{
if (double.Parse(rw["Quantity"].ToString()) > double.Parse(row["Quantity"].ToString()))
{
rw["Quantity"] = double.Parse(rw["Quantity"].ToString()) - double.Parse(row["Quantity"].ToString());
row["Quantity"] = 0;
}
else
{
row["Quantity"] = double.Parse(row["Quantity"].ToString()) - double.Parse(rw["Quantity"].ToString());
rw["Quantity"] = 0;
}
}
}
float denom = 0;
float numer = 0;
float avg = 0;
foreach (DataRow rw in dataTablebuy.Rows)
{
denom = denom + int.Parse(rw["Quantity"].ToString());
numer = numer + (int.Parse(rw["Quantity"].ToString()) * int.Parse(rw["price"].ToString()));
avg = numer / denom;
rw["Avg"] = avg;
}
GridView1.DataSource = dataTablebuy;
GridView1.DataBind();
ViewState["dataTablebuy"] = dataTablebuy;
GridView1.Visible = true;
Response.Write("average " +avg.ToString());
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
Response.Write("error" + sqlEx.ToString());
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}

Unable to retrieve a column value from different table in insert statement

I am trying to retrieve column value from another table and inserting into another table but can't resolve it no error but unable to resolve it. Empty column appears. Trying to insert t_vrm in insert statement on sql_fix_01 t_vrm is a varchar in SQL Server and its a vehicle registration number (number plate)
But returns empty column.
private void btnProcess_Click(object sender, EventArgs e)
{
tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ticket_reference", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("ticket_number", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("t_vrm", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("sql_fix_01", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("sql_fix_02", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("sql_fix_03", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("sql_fix_04", System.Type.GetType("System.String")));
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = stringConn;
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
string[] tempArray = new string[this.textBox1.Lines.Length];
tempArray = this.textBox1.Lines;
if (this.textBox1.Lines.Length == 0)
{
return;
}
myConn.Open();
int ticket_number = -666;
string t_vrm = "";
string sql_fix_01 = "";
string stringDatetime = DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
//string stringDatetime = "20120829 17:00:00";
for (int counter = 0; counter <= tempArray.Length - 1; counter++)
{
sql_fix_01 = "";
t_vrm = "";
ticket_number = -666;
if (tempArray[counter].Trim().Length > 0)
{
try
{
myComm.CommandText = "SELECT t_number, t_vrm FROM tickets WHERE t_reference='" + tempArray[counter] + "'";
ticket_number = (int)myComm.ExecuteScalar();
t_vrm = (string)(myComm.ExecuteScalar()).ToString();
MY ERROR IS IN THIS ROW.(t_vrm)
sql_fix_01 = "INSERT INTO [dvla] ([dvla_system_ref],[dvla_seq_no],[dvla_vrm],[dvla_due],[dvla_sent],[dvla_sent_by],[dvla_batch_no],[dvla_response_date],[dvla_query_destination]) VALUES(" + ticket_number.ToString().Trim() + ", 2 , t_vrm , '" + stringDatetime + "', NULL,'',0, NULL, 'DVLATicketLetter');";
}
catch { }
if (ticket_number != -666)
{
tbl.Rows.Add(tempArray[counter], ticket_number,t_vrm, sql_fix_01, sql_fix_02, sql_fix_03, sql_fix_04);
}
}
}
myConn.Close();
this.dataGridView1.DataSource = tbl;
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DataView vwExport = new DataView(tbl);
if (sfd.ShowDialog() == DialogResult.OK)
{
if (sfd.FileName != "")
{
btnProcess.Enabled = false;
Application.DoEvents();
StreamWriter sw = null;
FileStream fs = null;
fs = File.Open(sfd.FileName, FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine("USE ICPS");
sw.WriteLine("GO");
sw.WriteLine(" ");
sw.WriteLine("/* Set accounts Hold Status to ''VQ4 rescheduled' */");
sw.WriteLine(" ");
foreach (DataRowView drv in vwExport)
{
sw.WriteLine("/* Ticket Reference: " + drv["ticket_reference"].ToString() + "/" + drv["ticket_number"].ToString() + "/" + drv["t_vrm"].ToString() + "*/");
sw.WriteLine(drv["sql_fix_01"].ToString());
You cant use ExecuteScalar with multiple values..
myComm.CommandText = "SELECT t_number, t_vrm
FROM tickets WHERE t_reference='" + tempArray[counter] + "'";
ticket_number = (int)myComm.ExecuteScalar();
t_vrm = (string)(myComm.ExecuteScalar()).ToString();
You will need to use a DataReader instead.
SqlDataReader reader = myComm.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
ticket_number = reader.GetInt32(0);
t_vrm = reader.GetString(1);
}
Also, to reiterate what #Amber said, look at Bobby Tables, you really want to avoid dynamic SQL
Should'nt:
...VALUES(" + ticket_number.ToString().Trim() + ", 2 , t_vrm , '" +...
Be:
...VALUES(" + ticket_number.ToString().Trim() + ", 2 , " + t_vrm + " , '" +...
Your t_vrm variable is part of the string.

Add rows to the datagrid using foreach loop with dynamically returned query

I am trying to add rows to a datagrid where a condition is passed to query the data and get the results returned from that query to add to a datagrid. Below is the code:
private void FetchAllJobStatus(int regionID)
{
OleDbConnection con = new OleDbConnection(Constring);
String strQu1;
strQu1 = "SELECT LOGPATH, TWSID FROM JOB_DETAILS_TEST WHERE REGIONID = " + regionID + " ORDER BY TWSID";
OleDbDataAdapter dapt1 = new OleDbDataAdapter(strQu1, con);
DataTable dt1 = new DataTable();
dapt1.Fill(dt1);
foreach (DataRow row in dt1.Rows)
{
string twsIDName = row.ItemArray[1].ToString();
string startTime = GetStartTime(row.ItemArray[0].ToString(), int.Parse(twsIDName));
string endTime = GetEndTime(row.ItemArray[0].ToString(), int.Parse(twsIDName));
DateTime dat1 = DateTime.Parse(startTime);
DateTime dat2 = DateTime.Parse(endTime);
string endingTime;
if (endTime == string.Empty || endTime == null || dat2 < dat1)
{
endingTime = "";
}
else
{
endingTime = endTime.Remove(0, 3).ToString();
}
string startingTime = startTime.Remove(0, 3).ToString();
String strQu2;
strQu2 = "SELECT JOBNAME, TWSID, HIGHPRIORITY, DAY, TIME, '"+ startingTime + "' as StartTime, '"+ endingTime + "' as EndTime FROM JOB_DETAILS_TEST WHERE TWSID = " + int.Parse(twsIDName) + " AND REGIONID = " + regionID + " ORDER BY JOBNAME";
OleDbDataAdapter dapt2 = new OleDbDataAdapter(strQu2, con);
DataSet ds = new DataSet();
dapt2.Fill(ds, "dt2");
dgJobStatusAll.AutoGenerateColumns = true;
dgJobStatusAll.DataSource = ds;
dgJobStatusAll.DataMember = "dt2";
}
}
Here only the last data gets appended in the grid. Thanks in advance
Your finding is obvious because you bind the grid each time inside the foreach, hence every time its overwritten. Try to do it like this. This is not complete but should get you on track.
private void FetchAllJobStatus(int regionID)
{
OleDbConnection con = new OleDbConnection(Constring);
String strQu1;
strQu1 = "SELECT LOGPATH, TWSID FROM JOB_DETAILS_TEST WHERE REGIONID = " + regionID + " ORDER BY TWSID";
OleDbDataAdapter dapt1 = new OleDbDataAdapter(strQu1, con);
DataTable dt1 = new DataTable();
dapt1.Fill(dt1);
DataSet ds = new DataSet(); // Move this out
DataTable dt = new DataTable("MyTable");
dt.Columns.Add(new DataColumn("yourColumnName",typeof(int))); // Create columns as you want (your structure)
dt.Columns.Add(new DataColumn("yourColumnName2", typeof(string)));
foreach (DataRow row in dt1.Rows) // Now inside foreach create row and add it to the table
{
string twsIDName = row.ItemArray[1].ToString();
string startTime = GetStartTime(row.ItemArray[0].ToString(), int.Parse(twsIDName));
string endTime = GetEndTime(row.ItemArray[0].ToString(), int.Parse(twsIDName));
DateTime dat1 = DateTime.Parse(startTime);
DateTime dat2 = DateTime.Parse(endTime);
string endingTime;
if (endTime == string.Empty || endTime == null || dat2 < dat1)
{
endingTime = "";
}
else
{
endingTime = endTime.Remove(0, 3).ToString();
}
string startingTime = startTime.Remove(0, 3).ToString();
String strQu2;
strQu2 = "SELECT JOBNAME, TWSID, HIGHPRIORITY, DAY, TIME, '"+ startingTime + "' as StartTime, '"+ endingTime + "' as EndTime FROM JOB_DETAILS_TEST WHERE TWSID = " + int.Parse(twsIDName) + " AND REGIONID = " + regionID + " ORDER BY JOBNAME";
OleDbDataAdapter dapt2 = new OleDbDataAdapter(strQu2, con);
// dapt2.Fill(ds, "dt2");
DataRow dr = dt.NewRow(); // create row
dr["yourColumnName"] = // fill these
dr["yourColumnName2"] = // fill these
dt.Rows.Add(dr); // add row to dt
}
ds.Tables.Add(dt); // add table to your dataset
dgJobStatusAll.AutoGenerateColumns = true;
dgJobStatusAll.DataSource = ds;
dgJobStatusAll.DataMember = "dt2";
}
write a single query using union and fill the datatable out side the loop. Take
String strQu2;
out of the loop.And in loop use
if(string.IsNullOrEmpty(strQu2 ))
{
strQu2 ="SELECT JOBNAME, TWSID, HIGHPRIORITY, DAY, TIME, '"+ startingTime + "' as StartTime, '"+ endingTime + "' as EndTime FROM JOB_DETAILS_TEST WHERE TWSID = " + int.Parse(twsIDName) + " AND REGIONID = " + regionID ;
}
else
{
strQu2 =strQu2 +" Union All "+ "SELECT JOBNAME, TWSID, HIGHPRIORITY, DAY, TIME, '"+ startingTime + "' as StartTime, '"+ endingTime + "' as EndTime FROM JOB_DETAILS_TEST WHERE TWSID = " + int.Parse(twsIDName) + " AND REGIONID = " + regionID ;
}
And now After the loop write
strQu2 =strQu2 + " Order by REGIONID,JOBNAME "
And fill datatable and bind to grid
You can do it with DataTable.Merge(). take a DataTable instead of DataSet ds and before the for loop and bind the grid after the loop:
............................................
................................................
DataTable dt1 = new DataTable();
dapt1.Fill(dt1);
DataTable dtMain=new DataTable();
foreach (DataRow row in dt1.Rows)
{
string twsIDName = row.ItemArray[1].ToString();
string startTime = GetStartTime(row.ItemArray[0].ToString(), int.Parse(twsIDName));
string endTime = GetEndTime(row.ItemArray[0].ToString(), int.Parse(twsIDName));
DateTime dat1 = DateTime.Parse(startTime);
DateTime dat2 = DateTime.Parse(endTime);
string endingTime;
if (endTime == string.Empty || endTime == null || dat2 < dat1)
{
endingTime = "";
}
else
{
endingTime = endTime.Remove(0, 3).ToString();
}
string startingTime = startTime.Remove(0, 3).ToString();
String strQu2;
strQu2 = "SELECT JOBNAME, TWSID, HIGHPRIORITY, DAY, TIME, '"+ startingTime + "' as StartTime, '"+ endingTime + "' as EndTime FROM JOB_DETAILS_TEST WHERE TWSID = " + int.Parse(twsIDName) + " AND REGIONID = " + regionID + " ORDER BY JOBNAME";
OleDbDataAdapter dapt2 = new OleDbDataAdapter(strQu2, con);
DataTable dtTemp=new
dapt2.Fill(dtTemp);
if(dtTemp.Rows.Count>0)
{
dtMain.Merge(dtTemp);
}
}
dgJobStatusAll.AutoGenerateColumns = true;
dgJobStatusAll.DataSource = dtTemp;
//dgJobStatusAll.DataMember = "dt2";
}
or you can write single query with inner join which will be best this case .

Categories

Resources