How to get header name in autogenerated GridView - c#

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>

Related

Remove row from datatable if column is not numeric [closed]

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();

Public void exporttoexcel(datagridview gridviewid, string excelfilename) {

I am trying to export the data from the ACCDB file to Excel.
and its working but when I am export in excel file is empty there is no data.
Below is code
What I have tried:
{
private void btnExport_Click(object sender, EventArgs e)
{
ExportToExcel(dataGridView1,"ExportedUserDetail");
}
public void ExportToExcel(DataGridView gridviewID, string excelFilename)
{
DateTime from = dateTimePicker1.Value;
string date1 = from.ToString("MM/dd/yyyy");
string fromdate = date1 + " " + "12:00:00" + " " + "AM";
DateTime to = dateTimePicker2.Value;
string date2 = to.ToString("MM/dd/yyyy");
string todate = date2 + " " + "11:00:00" + " " + "PM";
if (dateTimePicker1.Value != dateTimePicker2.Value)
{
string ConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Data\Test.accdb";
DataTable Data = new DataTable();
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
conn.Open();//break
OleDbCommand cmd = new OleDbCommand("select tb3.SeqNo as 'Session Sequence Number',tb3.SessionDate as 'Session Date',tb3.CustomerName as 'Customer Name',tb3.RepID as 'Rep ID',tb3.RepName as 'Rep Name',CaseRef as 'Ticket No',PracticeName as 'Practice Name',PostCode as 'Post Code',PhoneManner as 'Phone Manner',Satisfaction,iif (Satisfaction='EXCELLENT',5, iif (Satisfaction='VERY GOOD' ,4, iif (Satisfaction='GOOD' ,3, iif (Satisfaction='NEUTRAL' ,2, iif (Satisfaction='POOR' ,1))))) as Ratings,Ratings/5*100 as 'Percentage' , Consultant,CustomerComments as 'Customer Comments',Recommendation from tb1,tb3 where tb3.SeqNo=tb1.SeqNo and tb3.SessionDate between #" + fromdate + "# and #" + todate + "#", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
dataGridView1.DataSource = Data;
Microsoft.Office.Interop.Excel.Application objexcelapp = new Microsoft.Office.Interop.Excel.Application();
objexcelapp.Application.Workbooks.Add(Type.Missing);
objexcelapp.Columns.ColumnWidth = 25;
for (int i = 1; i < gridviewID.Columns.Count + 1; i++)
{
objexcelapp.Cells[1, i] = gridviewID.Columns[i - 1].HeaderText;
}
/*For storing Each row and column value to excel sheet*/
for (int i = 0; i < gridviewID.Rows.Count; i++)
{
for (int j = 0; j < gridviewID.Columns.Count; j++)
{
if (gridviewID.Rows[i].Cells[j].Value != null)
{
objexcelapp.Cells[i + 2, j + 1] = gridviewID.Rows[i].Cells[j].Value.ToString();
}
}
}
MessageBox.Show("Your excel file exported successfully at d:\\" + excelFilename + ".xlsx");
objexcelapp.ActiveWorkbook.SaveCopyAs("d:\\" + excelFilename + ".xlsx");
objexcelapp.ActiveWorkbook.Saved = true;
}
}
else
{
MessageBox.Show("Please select valid date...!!!");
}
}
}
}
Hello,
I am trying to export the data from the ACCDB file to Excel.
and its working but when I am export in excel file is empty there is no data.

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());
}
}

Sum of Gridview columns/rows ASP.NET C#

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!

Import Excel file with header and sub header in to database

I have excel sheet like below
Condom Lubricant
dic_code condom_receive lubricant_receive
3 100 50
1 150 0
2 270 78
I want import in to database like following way
dic_code condom_receive lubricant_receive
3 100 0
3 0 50
1 150 0
1 0 0
2 270 0
2 0 78
I have write code using C# and ASP.net. But its not working. Please help me out.
protected void importBtn_Click(object sender, EventArgs e)
{
var folder = Server.MapPath("~/temp/");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (FileUpload1.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
OleDbcon.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
objAdapter1.Fill(ds);
dt = ds.Tables[0];
OleDbcon.Close();
int number_of_columns = dt.Columns.Count;
int number_of_rows = ds.Tables[0].Rows.Count;
string[,] sheetEntries = new string[number_of_rows, number_of_columns];
string[] columnNames = new string[number_of_columns];
for (int j = 0; j < number_of_columns; j++)
{
columnNames[j] = dt.Columns[j].ToString();
}
for (int i = 0; i < number_of_rows; i++)
{
for (int j = 0; j < number_of_columns; j++)
sheetEntries[i, j] = dt.Rows[i].ItemArray.GetValue(j).ToString();
}
string strSQL1 = null;
for (int i1 = 0; i1 < number_of_rows; i1++)
{
if (sheetEntries[0, 1] == "Condom")
{
strSQL1 = "INSERT INTO [import_test]([dic_code],[condom_receive],[lubricant_receive]) VALUES ("
+ sheetEntries[i1, 0] + ",'" + sheetEntries[i1, 1] + "'," + 0 + ");";
SqlCommand cmd1 = new SqlCommand(strSQL1);
dc.Open();
cmd1.Connection = dc.GetConnection();
cmd1.ExecuteNonQuery();
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
Label1.ForeColor = Color.Green;
Label1.Text = "Successfully inserted";
dc.Close();
}
if (sheetEntries[0, 2] == "Lubricant")
{
strSQL1 = "INSERT INTO [import_test]([dic_code],[condom_receive],[lubricant_receive]) VALUES ("
+ sheetEntries[i1, 0] + ",'" + 0 + "'," + sheetEntries[i1, 1] + ");";
SqlCommand cmd1 = new SqlCommand(strSQL1);
dc.Open();
cmd1.Connection = dc.GetConnection();
cmd1.ExecuteNonQuery();
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
Label1.ForeColor = Color.Green;
Label1.Text = "Successfully inserted";
dc.Close();
}
}
}
else
{
Label1.ForeColor = Color.Red;
Label1.Text = "Please select the File";
}
}
I have change my code following way. And its working
protected void importBtn_Click(object sender, EventArgs e)
{
var folder = Server.MapPath("~/temp/");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (FileUpload1.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);
//OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$a2:j]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
OleDbcon.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
objAdapter1.Fill(ds);
dt = ds.Tables[0];
OleDbcon.Close();
int number_of_columns = dt.Columns.Count;
string[] columnNames = new string[number_of_columns];
int k;
for (k = 0; k < number_of_columns; k++)
{
columnNames[k] = dt.Columns[k].ToString();
}
if (columnNames[0] == "v"|| columnNames[1] == "Condom" || columnNames[2] == "Lubricant")
{
OleDbCommand cl_cmd = new OleDbCommand("SELECT * FROM [Sheet1$a2:j]", OleDbcon);
OleDbDataAdapter objAdapter2 = new OleDbDataAdapter(cl_cmd);
OleDbcon.Open();
DataSet ds1 = new DataSet();
DataTable dt1 = new DataTable();
objAdapter2.Fill(ds1);
dt1 = ds1.Tables[0];
OleDbcon.Close();
int number_of_columns1 = dt1.Columns.Count;
string[] columnNames1 = new string[number_of_columns1];
int number_of_rows = ds1.Tables[0].Rows.Count;
string[,] sheetEntries = new string[number_of_rows, number_of_columns];
for (int j = 0; j < number_of_columns1; j++)
{
columnNames1[j] = dt1.Columns[j].ToString();
}
for (int i = 0; i < number_of_rows; i++)
{
for (int j = 0; j < number_of_columns1; j++)
sheetEntries[i, j] = dt1.Rows[i].ItemArray.GetValue(j).ToString();
}
string strSQL1 = null;
for (int i1 = 0; i1 < number_of_rows; i1++)
{
if (columnNames[1] == "Condom")
{
strSQL1 = "INSERT INTO [import_test]([dic_code],[condom_receive],[lubricant_receive]) VALUES ("
+ sheetEntries[i1, 0] + ",'" + sheetEntries[i1, 1] + "'," + 0 + ");";
SqlCommand cmd1 = new SqlCommand(strSQL1);
dc.Open();
cmd1.Connection = dc.GetConnection();
cmd1.ExecuteNonQuery();
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
Label1.ForeColor = Color.Green;
Label1.Text = "Successfully inserted";
dc.Close();
}
if (columnNames[2] == "Lubricant")
{
strSQL1 = "INSERT INTO [import_test]([dic_code],[condom_receive],[lubricant_receive]) VALUES ("
+ sheetEntries[i1, 0] + ",'" + 0 + "'," + sheetEntries[i1, 1] + ");";
SqlCommand cmd1 = new SqlCommand(strSQL1);
dc.Open();
cmd1.Connection = dc.GetConnection();
cmd1.ExecuteNonQuery();
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
Label1.ForeColor = Color.Green;
Label1.Text = "Successfully inserted";
dc.Close();
}
}
}
}
else
{
Label1.ForeColor = Color.Red;
Label1.Text = "Please select the File";
}
}

Categories

Resources