I want to make sums of columns and rows in a gridview , I tried so many ways and I can't do it. I'm trying to understand what's wrong. I'm sorry If my code is a mess. I'm using ASP.NET C#. For now it is enough to show sum only in a response.write, later i'll put it on a column/row.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=*****;Initial Catalog=***;User=***;password=**");
//query para o select das especialidades todas
string specstring = "SELECT Speciality.Shortname, SUM(1) as contar " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
" GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
" WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
" GROUP BY Speciality.Shortname ";
SqlCommand command = new SqlCommand(specstring, conn);
command.Connection.Open();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = command;
DataTable specstringtable = new DataTable();
myDataAdapter.Fill(specstringtable);
specstring = "";
for (int i = 0; i < specstringtable.Rows.Count; i++)
{
if (specstring == "")
{
specstring = "[" + specstringtable.Rows[i][0] + "]".ToString();
}
else
{
specstring = specstring + ", " + "[" + specstringtable.Rows[i][0] + "]";
}
}
command.Connection.Close();
////query para a pivot table
string querystring = "SELECT Description AS Categoria, " + specstring +
"FROM (SELECT GroupType.Description, Speciality.Shortname, SUM(1) AS contar, GroupType.GroupId " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
"GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
"WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
"GROUP BY GroupType.Description, Speciality.Shortname, DoctorEnterpriseDetails.GroupId, GroupType.GroupId) as ps " +
"PIVOT (SUM(contar) FOR Shortname IN (" + specstring + ")) pvt " +
"ORDER BY GroupId; ";
////Response.Write(querystring);
SqlCommand command2 = new SqlCommand(querystring, conn);
command2.Connection.Open();
SqlDataAdapter myDataAdapter2 = new SqlDataAdapter();
myDataAdapter2.SelectCommand = command2;
DataTable cobtable = new DataTable();
myDataAdapter2.Fill(cobtable);
DataColumn cl = cobtable.Columns.Add("Total");
cobtable.Columns["Total"].SetOrdinal(1);
DataRow dr;
dr = cobtable.NewRow();
dr["Categoria"] = "Total";
cobtable.Rows.InsertAt(dr, 0);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 1);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 3);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 4);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 6);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 7);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 9);
GroupGrid.DataSource = cobtable;
GroupGrid.DataBind();
//GroupGrid.FooterRow.Cells[1].Text = cobtable.Compute("sum(" + cobtable.Columns[3].ColumnName + ")", null).ToString();
decimal a = 0, soma = 0;
string la = "";
//Response.Write(GroupGrid.Rows[0].Cells.Count);
for (int i = 3; i <= (GroupGrid.Rows[0].Cells.Count); i++)
{
Response.Write("!");
//string l3 = GroupGrid.Rows[6].Cells[i-1].Text;
// Response.Write(l3);
Response.Write(GroupGrid.Rows[5].Cells[i - 1].Text);
// la = GroupGrid.Rows[5].Cells[i - 1].Text;
// sum += Convert.ToInt32(la);
//sum = Convert.ToInt32(GroupGrid.Rows[5].Cells[i - 1].Text.ToString());
//a = a + sum;
//GroupGrid.FooterRow.Cells[1].Text = sum.ToString();
}
// Response.Write(a.ToString());
You are right your code is a little mess ;)
I tried to understand what you mean so just for a case here you have the example how to sum the values in row, sum the values in column or some both columns and rows so sum of all cells.
These examples assume you are not having cells spaning through more then one row or column and that the total sum of your values is less then "long" size and each cell contains number that is "integer".
public void DisplayGridViewSums(GridView gv)
{
foreach (GridViewRow row in gv.Rows)
{
long sum = SumValuesInRow(row);
Console.WriteLine("Sum of values in raw '{0}' is: {1}", row.RowIndex, sum);
}
for (int i=0; i<gv.Columns.Count;i++)
{
long sum = SumValuesInColumn(gv,i);
Console.WriteLine("Sum of values in column '{0}' with header '{1}' is: {2}",i, gv.Columns[i].HeaderText, sum);
}
long totalsum = SumColumnsAndRowsInGridView(gv);
Console.WriteLine("Sum of all cells in each row is: {0}", totalsum);
}
public long SumColumnsAndRowsInGridView(GridView gv)
{
long sum = 0;
foreach (GridViewRow row in gv.Rows)
{
sum += SumValuesInRow(row);
}
return sum;
}
public long SumValuesInRow(GridViewRow row)
{
long sum = 0;
foreach (TableCell cell in row.Cells)
{
sum += int.Parse(cell.Text);
}
return sum;
}
public long SumValuesInColumn(GridView gv, int columnIndx)
{
long sum = 0;
foreach (GridViewRow row in gv.Rows)
{
sum += int.Parse(row.Cells[columnIndx].Text);
}
return sum;
}
First method shows the sums on console. The other count the sums for particular GridView. Those counting methods could be written using Linq but for your convenience a left them as simple for and foreach loops.
Hope it solves your problem!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a datatable with a few columns. The first column is our employee id. Unfortunately not all of the rows are numeric and we want to remove those who aren't numeric. For instance, we have 1 row which has "##$" and I want to remove rows like these. I currently have the following code.
var len = dt.Rows.Count;
for(int y = 0; y < len; y++)
{
var mwd = dt.Columns[0].ToString();
bool valid = int.TryParse(mwd, out int n);
if (valid)
{
log.LogInformation("mwd is numeric");
}
else
{
log.LogInformation("mwd is not numeric");
dt.Rows[y].Delete();
}
}
However, this doesn't remove the row. What am I doing wrong? Thanks in advance.
EDIT: Surrounding code
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string[] columns = { "Mwd", "Naam", "Kostenplaats Externe id (Klant)", "Kostenplaats Loonlijstcode (Activiteit)", "Kostenplaats Naam (Activiteit)", "Datum", "Uren ruw", "Ber. Uren", "Verlof volledig pad" };
foreach (string column in columns)
{
dt.Columns.Add(column);
}
using (StreamReader reader = new StreamReader(req.Body))
{
while (reader.EndOfStream == false)
{
string[] rows = reader.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < columns.Length; i++)
{
var temp = rows[i].Trim('"');
dr[i] = temp.Trim('\'');
}
dt.Rows.Add(dr);
}
}
for (int i = 0; i < dt.Rows.Count; i++)
{
foreach (DataColumn column in dt.Columns)
{
var mwd = dt.Rows[i][column].ToString();
int n;
bool valid = int.TryParse(mwd, out n);
if (valid)
{
log.LogInformation("mwd is numeric");
}
else
{
log.LogInformation("mwd is not numeric");
dt.Rows[i].Delete();
i--;
break;
}
}
}
dt.AcceptChanges();
log.LogInformation(dt.ToString());
for (int x = 0; dt.Rows.Count > x; x++)
{
string sql = "INSERT INTO dbo.kronos (Mwd, Naam, KostenplaatsExterneIdKlant, KostenplaatsLoonlijstcodeActiviteit, KostenplaatsNaamActiviteit, Datum, UrenRuw, BerUren, VerlofVolledigPad)" +
" VALUES ('" + dt.Rows[x]["Mwd"].ToString() + "', '" + dt.Rows[x]["Naam"].ToString() + "', '"
+ dt.Rows[x]["Kostenplaats Externe id (Klant)"].ToString() + "', '" + dt.Rows[x]["Kostenplaats Loonlijstcode (Activiteit)"].ToString() + "', '"
+ dt.Rows[x]["Kostenplaats Naam (Activiteit)"].ToString() + "', '" + dt.Rows[x]["Datum"].ToString() + "', '"
+ dt.Rows[x]["Uren ruw"].ToString() + "', '" + dt.Rows[x]["Ber. Uren"].ToString() + "', '" + dt.Rows[x]["Verlof volledig pad"].ToString() + "')";
var str = Environment.GetEnvironmentVariable("ConnectionString");
using (SqlConnection connection = new SqlConnection(str))
{
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
command.ExecuteNonQuery();
}
}
return result;
try this code
for (int i = 0; i< dt.Rows.Count;i++)
{
foreach (DataColumn column in dt.Columns)
{
var mwd = dt.Rows[i][column].ToString();
int n;
bool valid = int.TryParse(mwd, out n);
if (valid)
{
log.LogInformation("mwd is numeric");
}
else
{
log.LogInformation("mwd is not numeric");
dt.Rows[i].Delete();
i--;
break;
}
}
}
dt.AcceptChanges();
If you know the name of the column or its index, use the following code
for (int i = 0; i < dt.Rows.Count; i++)
{
var mwd = dt.Rows[i]["Name"].ToString();
//or---------------------------------
var mwd = dt.Rows[i][index].ToString();
int n;
bool valid = int.TryParse(mwd, out n);
if (valid)
{
log.LogInformation("mwd is numeric");
}
else
{
log.LogInformation("mwd is not numeric");
dt.Rows[i].Delete();
i--;
}
}
dt.AcceptChanges();
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.
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());
}
}
Is there anyway to fill an multidimensional array with a sql query? My sql query results on a pivot table. As you can see, I want so make some sums (for Total Column and Total Row) and I want to know the best way to make that sums and percentages in that table.. I said multidimensional array because it could be easier. The code below works but I want to know how can I choose the rows and columns to make the sums. I'm using ASP.NET C#
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=****;Initial Catalog=***;User=sa;password=***");
//query for all specialities
string specstring = "SELECT Speciality.Shortname, SUM(1) as contar " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
" GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
" WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
" GROUP BY Speciality.Shortname ";
SqlCommand command = new SqlCommand(specstring, conn);
command.Connection.Open();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = command;
// Adds rows in the DataSet
//DataSet myDataSet = new DataSet();
DataTable specstringtable = new DataTable();
myDataAdapter.Fill(specstringtable);
specstring = "";
for (int i = 0; i < specstringtable.Rows.Count; i++)
{
if (specstring == "")
{
specstring = "[" + specstringtable.Rows[i][0] + "]".ToString();
}
else
{
specstring = specstring + ", " + "[" + specstringtable.Rows[i][0] + "]";
}
}
//GroupGrid.DataSource = cobtable;
//GroupGrid.DataBind();
command.Connection.Close();
////query for pivot table
string querystring = "SELECT Description AS Categoria, " + specstring +
"FROM (SELECT GroupType.Description, Speciality.Shortname, SUM(1) AS contar, GroupType.GroupId " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
"GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
"WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
"GROUP BY GroupType.Description, Speciality.Shortname, DoctorEnterpriseDetails.GroupId, GroupType.GroupId) as ps " +
"PIVOT (SUM(contar) FOR Shortname IN (" + specstring + ")) pvt " +
"ORDER BY GroupId; ";
////Response.Write(querystring);
SqlCommand command2 = new SqlCommand(querystring, conn);
command2.Connection.Open();
SqlDataAdapter myDataAdapter2 = new SqlDataAdapter();
myDataAdapter2.SelectCommand = command2;
// Adds rows in the DataSet
//DataSet myDataSet2 = new DataSet();
DataTable cobtable = new DataTable();
myDataAdapter2.Fill(cobtable);
DataColumn cl = cobtable.Columns.Add("Total");
cobtable.Columns["Total"].SetOrdinal(1);
DataRow dr;
dr = cobtable.NewRow();
dr["Categoria"] = "Total";
cobtable.Rows.InsertAt(dr, 0);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 1);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 3);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 4);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 6);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 7);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 9);
GroupGrid.DataSource = cobtable;
GroupGrid.DataBind();
}
c
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.