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();
Related
try
{
string CSVFilePathName = textBox4.Text;
for (int i = 0; i < CSVFilePathName.Length; i++)
{
if (CSVFilePathName[i] == '\\')
{
CSVFilePathName.Insert(i + 1, "\\");
}
}
if (string.IsNullOrWhiteSpace(textBox4.Text))
{
MessageBox.Show("Please Select a File");
}
else
{
int count = 0;
// your code here
// string CSVFilePathName = #"'" + textBox4.Text + "'";
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
for (int f = 0; f < Cols; f++)
{
q = "SELECT * from questions where main_section='" + Fields[0] + "' AND secondary_section='" + Fields[1] + "' AND tert_section='" + Fields[2] + "' AND question='" + Fields[3] + "' AND difficulty='" + Fields[4] + "'";
OleDbCommand cmdn = new OleDbCommand(q, conn);
//MessageBox.Show(q);
object obj = cmdn.ExecuteScalar();
if (obj == null)
{
q = "insert into questions values('" + Fields[0] + "','" + Fields[1] + "','" + Fields[2] + "','" + Fields[3] + "' ,'" + Fields[4] + "')";
OleDbCommand cmdn1 = new OleDbCommand(q, conn);
cmdn1.ExecuteNonQuery();
}
else
{
count++;
}
//MessageBox.Show(Fields[f]);
}
}
// dataGridClients.DataSource = dt;
string msg = "Upload successful\n";
if (count > 0)
{
msg=count.ToString()+" Questions missed due to their duplicates in the database.";
}
MessageBox.Show(msg);
}
}
catch (Exception ex)
{
MessageBox.Show("Error is " + ex.ToString());
throw;
}
I am using c# winform to upload a csv file to my ms access db, but it is givig the error "The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data." What should do now?
I suggest specifying the table fields in the SQL like
INSERT INTO questions (fieldname1, fieldname2, ...) VALUES (...)
Use parameterized-values rather than writing the values directly in the string. This also allows you to specify the datatype and then the ADO.Net OLE adapter will hopefully handle it appropriately and get the long text inserted with no trouble. Go to Read / Write BLOBs ... for an example inserting BLOBS. The concept and code example are very relevant to inserting Long Text values. It demonstrates how to set up parameters for the query. In your case, use OleDbType.LongVarWChar for the Long Text fields.
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>
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!
At first I tried this:
string set = "";
for (int i = 1; i < result.Count; i++)
{
if ((fieldtypes[i] == "System.Int32"))
{
set += fields[i] + "=" + result[i] + ", ";
}
else if (fieldtypes[i] == "System.String")
{
set += fields[i] + "='" + result[i] + "', ";
}
else if (fieldtypes[i] == "System.Boolean")
{
set += fields[i] + "=" + result[i] + ", ";
}
else if (fieldtypes[i] == "System.DateTime")
{
set += fields[i] + "='#" + System.DateTime.Now + "#', ";
}
}
set = set.Substring(0, set.Length - 2);
string sql11 = "UPDATE [Contacts] SET " + set + " WHERE pkContactID=" + cKey;
OleDbCommand myCommand11 = new OleDbCommand(sql11, myConnection);
myCommand11.ExecuteNonQuery();
Now this WORKED when I omitted the string and datetime conditions so that it only updated the int and boolean. So it has something to do with a syntax error when I try to update a field where the type is a string.
Then I heard that you have to use parameters when writing to an .mdb file, so I tried this:
string sql11 = "UPDATE [Contacts] SET ";
for (int i = 1; i < result.Count; i++)
{
sql11 += fields[i] + " = ?, ";
}
sql11 = sql11.Substring(0, sql11.Length - 2);
sql11 += " WHERE pkContactID = " + cKey;
using (myConnection)
{
using (OleDbCommand myCommand11 = new OleDbCommand(sql11, myConnection))
{
myCommand11.CommandType = CommandType.Text;
for (int j = 1; j < result.Count; j++)
{
if (fieldtypes[j] == "System.Int32")
{
myCommand11.Parameters.AddWithValue(fields[j], int.Parse(result[j]));
}
else if (fieldtypes[j] == "System.String")
{
myCommand11.Parameters.AddWithValue(fields[j], result[j]);
}
else if (fieldtypes[j] == "System.Boolean")
{
myCommand11.Parameters.AddWithValue(fields[j], Boolean.Parse(result[j]));
}
else if (fieldtypes[j] == "System.DateTime")
{
myCommand11.Parameters.AddWithValue(fields[j], DateTime.Now);
}
}
Console.WriteLine(sql11);
myCommand11.ExecuteNonQuery();
}
}
}
Which did not work either. I don't think the ?'s are being replaced properly.
Anyway, please help me fix it so that I can update properly.
Instead of having to mess around with the UPDATE query string for Access, which is easily prone to syntax errors, I just created a DataTable object and SELECTed the row I wanted to UPDATE. I then updated the table via an array of the elements that I wanted to change, then updated the table back to the server using an adapter. This worked out well without me worrying about the syntax! :)
Cheers
Well, I am doing a project on online movie ticket booking.
My problem is, I want to show the seating arrangement in a screen of a particular theater.
As in every row the number of seats can vary so what I have done is add a panel and in it a checkboxlist is dynamically added during runtime.
each checkboxlist represents a single row.
string s;
for (int i = 0; i < ds.Tables["row_id_no_of_seats"].Rows.Count; i++)
{
cbl = new CheckBoxList();
cbl.RepeatDirection = 0; //horizontal
cbl.RepeatLayout = 0; //table
cbl.RepeatColumns = (int)ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[1];
Panel1.Controls.Add(cbl);
for(int j=1;j<=(int)ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[1];j++)
{
s = ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[0].ToString() + j.ToString(); //ex:A+1
cbl.Items.Add(s);
string query1 = "select booking_detail.row_id,booking_detail.column_id from booking_detail,booking where (booking_detail.booking_id=booking.booking_id) and (booking_detail.booking_date='" + bk_date + "') and (booking.booking_date='" + bk_date + "') and (booking.theatre_id=" + theatre_id + ") and (booking.screen_id=" + screen_id + ") and (booking.movie_id=" + movie_id + ") and (booking.show_start_time='" + show_start_time + "') and (booking.class_id=" + class_id + ")";
SqlCommand command1 = new SqlCommand(query1, connection);
adapter.SelectCommand = command1;
adapter.Fill(ds, "seat_booked_info");
// it checks and disables the seats which have been pre- booked.
for (int k = 0; k < ds.Tables["seat_booked_info"].Rows.Count;k++) {
if(ds.Tables["seat_booked_info"].Rows[k].ItemArray[0].ToString().Equals(ds.Tables["row_id_no_of_seats"].Rows[i].ItemArray[0].ToString())) && (ds.Tables["seat_booked_info"].Rows[k].ItemArray[1].ToString().Equals(j.ToString())))
{
cbl.Items.FindByText(s).Selected=true;
cbl.Items.FindByText(s).Enabled = false;
}
}
ds.Tables["seat_booked_info"].Clear();
}
}
Now what I want is, how do I get the details of the checkbox which have been selected by the user as the checkboxlist are dynamically added to the panel?
You would use something like this:
foreach (Control c in Panel1.Controls)
{
CheckBoxList list = c as CheckBoxList;
if (c != null)
{
// Do something with the list
}
}