Import Excel file with header and sub header in to database - c#

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";
}
}

Related

System.Data.SqlClient.SqlException: 'Invalid column name 'P1000'.'

Can anybody help me? Why am I getting this error?
If I remove the 'P' from the prod_id which left only number, it can work but if I add alphabet, it says "Invalid column name".
I already added .ToString() to it, but why it still can't take varchar and only take int.
Here is my code
public partial class AddtoCart : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(Global.cs);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Username"] == null)
{
Response.Redirect("Authentication.aspx");
}
// Adding product to Gridview
Session["addproduct"] = "false";
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("Id");
dt.Columns.Add("Pname");
dt.Columns.Add("Pimage");
dt.Columns.Add("Pprice");
dt.Columns.Add("Pquantity");
dt.Columns.Add("Ptotal");
if (Request.QueryString["Id"] != null)
{
if (Session["buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection conn = new SqlConnection(Global.cs);
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
dr["Pquantity"] = Request.QueryString["quantity"];
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int TotalPrice = price * Quantity;
dr["Ptotal"] = TotalPrice;
dt.Rows.Add(dr);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
Button1.Enabled = true;
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
Response.Redirect("AddtoCart.aspx");
}
else
{
dt = (DataTable)Session["buyitems"];
int sr;
sr = dt.Rows.Count;
dr = dt.NewRow();
SqlConnection conn = new SqlConnection(Global.cs);
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["id"], conn);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = sr + 1;
dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
dr["Pquantity"] = Request.QueryString["quantity"];
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int TotalPrice = price * Quantity;
dr["Ptotal"] = TotalPrice;
dt.Rows.Add(dr);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
Button1.Enabled = true;
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
Response.Redirect("AddtoCart.aspx");
}
}
else
{
dt = (DataTable)Session["buyitems"];
GridView1.DataSource = dt;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
}
}
}
if (GridView1.Rows.Count.ToString() == "0")
{
Button3.Enabled = false;
Button1.Enabled = false;
}
else
{
Button3.Enabled = true;
Button1.Enabled = true;
}
}
// 2.Calculating Final Price
public int grandtotal()
{
DataTable dt = new DataTable();
dt = (DataTable)Session["buyitems"];
int nrow = dt.Rows.Count;
int i = 0;
int totalprice = 0;
while (i < nrow)
{
totalprice = totalprice + Convert.ToInt32(dt.Rows[i]["Ptotal"].ToString());
i = i + 1;
}
return totalprice;
}
// 4. Deleting Row From Cart
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["buyitems"];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
int sr;
int sr1;
string qdata;
string dtdata;
sr = Convert.ToInt32(dt.Rows[i]["sno"].ToString());
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
qdata = cell.Text;
dtdata = sr.ToString();
sr1 = Convert.ToInt32(qdata);
TableCell prID = GridView1.Rows[e.RowIndex].Cells[1];
if (sr == sr1)
{
dt.Rows[i].Delete();
dt.AcceptChanges();
conn.Open();
SqlCommand cmd = new SqlCommand("Delete top (1) from Cart where product_id='" + prID.Text + "' and username= '" + Session["username"] + "' ", conn);
cmd.ExecuteNonQuery();
conn.Close();
//Item Has Been Deleted From Shopping Cart
break;
}
}
// 5. Setting SNo. after deleting Row item from cart
for (int i = 1; i <= dt.Rows.Count; i++)
{
dt.Rows[i - 1]["sno"] = i;
dt.AcceptChanges();
}
Session["buyitems"] = dt;
Response.Redirect("AddtoCart.aspx");
}
// 6. Button Click
protected void Button1_Click(object sender, EventArgs e)
{
bool isTrue = false;
DataTable dt = (DataTable)Session["buyitems"];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
//SqlConnection conn = new SqlConnection(Global.cs);
//conn.Open();
//SqlCommand cmd = new SqlCommand("insert into Cart(sno,product_id,product_name,product_price,product_quantity,username) values('" + dt.Rows[i]["sno"] + "','" + dt.Rows[i]["Id"] + "','" + dt.Rows[i]["Pname"] + "','" + dt.Rows[i]["Pprice"] + "','" + dt.Rows[i]["Pquantity"] + "','" + Session["Username"] + "')", conn);
//cmd.ExecuteNonQuery();
//conn.Close();
int pId = Convert.ToInt16(dt.Rows[i]["Id"]);
int pQuantity = Convert.ToInt16(dt.Rows[i]["Pquantity"]);
SqlDataAdapter sda = new SqlDataAdapter("Select stock_count, prod_name from Product2 where prod_id='" + pId + "' ", conn);
DataTable dtble = new DataTable();
sda.Fill(dtble);
int quantity = Convert.ToInt16(dtble.Rows[0][0]);
if(quantity == 0)
{
string pName = dtble.Rows[0][1].ToString();
string msg = "" + pName + " is not in Stock";
Response.Write("<script>alert('" + msg + "');</script>");
isTrue = false;
}
}
if (GridView1.Rows.Count.ToString() == "0")
{
Response.Write("<script>alert('Your Cart is Empty. You cannot place an Order');</script>");
}
else
{
if (isTrue == true)
{
Response.Redirect("Checkout2.aspx");
}
}
// If Session is Null Redirecting to login else Placing the order
if (Session["Username"] == null)
{
Response.Redirect("Authentication.aspx");
}
else
{
Response.Redirect("Checkout2.aspx");
}
}
public void clearCart()
{
conn.Open();
SqlCommand cmd = new SqlCommand("Delete from Cart where username='" + Session["Username"] + "' ", conn);
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("AddtoCart.aspx");
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["buyitems"] = null;
clearCart();
}
}
This is the database table
CREATE TABLE [dbo].[Product2]
(
[prod_id] VARCHAR(6) NOT NULL,
[prod_name] VARCHAR(50) NOT NULL,
[prod_price] FLOAT(53) NOT NULL,
[prod_desc] VARCHAR(120) NOT NULL,
[prod_img] NVARCHAR(MAX) NOT NULL,
[prod_cat] VARCHAR(6) NOT NULL,
[stock_count] INT NULL,
[weight] DECIMAL(9, 2) NULL,
[width] DECIMAL(9, 2) NULL,
[length] DECIMAL(9, 2) NULL,
[height] DECIMAL(9, 2) NULL,
[shipping_fee] DECIMAL(9, 2) NOT NULL,
[created_at] DATETIME NOT NULL,
[updated_at] DATETIME NULL,
[prod_status] NVARCHAR(MAX) NULL,
PRIMARY KEY CLUSTERED ([prod_id] ASC),
CONSTRAINT [FK_Product2_ToTable]
FOREIGN KEY ([prod_cat]) REFERENCES [dbo].[Category] ([cat_id])
);
The way you pass the query could lead to SQL Injection.
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);
I expect the final query you want to achieve is
select * from Product2 where prod_id=`P100`
But after revise your code if you do concatenate with 'P' in your query, you will get:
select * from Product2 where prod_id=P100
In which this will return result:
Invalid column name 'P100'
String concatenation into query is dangerous that possible break your query.
You need to create a SqlCommand variable and pass it to the SqlDataAdapter.
And also use SqlParameter to pass the parameter value.
SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con);
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
After create and initialize SqlCommand, then you pass it into SqlDataAdpater as below
SqlDataAdapter da = new SqlDataAdapter(cmd);
Additional recommendation:
Use using block for your SqlConnection, SqlCommand and SqlDataAdapter as these (implemented with IDisposable interface) will automatically dispose the resources once the process is ended or exception is triggered.
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(Global.cs))
{
using (SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con))
{
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
Updated answer with credited to #Tim Schmelter's suggestion
For Using declarations in C#8.0, you are not required to add scope for the using block.
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
DataSet ds = new DataSet();
using SqlConnection conn = new SqlConnection(Global.cs);
using SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con);
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
using SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

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 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>

Only 1 column is added to my MySQLDB from Excel File

I am trying to insert data from Excel file to Mysql DB. It works but the problem is, it insert just 1 column. I need to insert all the column from my Excel file
Here is my Code
protected void add_Click(object sender, EventArgs e)
{
if (importfile.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + importfile.FileName)));
importfile.PostedFile.SaveAs(path);
OleDbConnection oleConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 8.0;");
OleDbCommand oleCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oleConn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCmd);
DataSet ds = new DataSet();
oleAdapter.Fill(ds);
DataTable Dt = new DataTable();
Dt = ds.Tables[0];
string userId = (string)(Session["id"]);
string groupName = groupname.Text.ToString();
try {
for (int i = 0; i < Dt.Rows.Count; i++)
{
DataRow row = Dt.Rows[i];
int columnCount = Dt.Columns.Count;
string[] columns = new string[columnCount];
for (int j = 0; j < columnCount; j++)
{
columns[j] = row[j].ToString();
}
conn.Open();
string sql = "INSERT INTO contacts(user_id, idNum, contact_name, contact_number, group_name)";
sql += "VALUES('" + userId + "','" + columns[0] + "','" + columns[1] + "','" + columns[2] + "','" + groupName + "')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
string message = "Success!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload = function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "alert", sb.ToString());
Response.Redirect("viewgroups.aspx");
conn.Close();
}
}
}
catch (Exception)
{
string message = "Failed!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload = function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "alert", sb.ToString());
}
Having very hard time with this. Please help. Thanks

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

Categories

Resources