Export Gridview to excel datatable in Asp.net - c#

I have a gridview in .net which needs to be exported to excel/datable.Problem is
it contains textbox+dropdowns. This does not work for dropdowns
public void Persist(object sender, EventArgs e)
{
// GridViewExportUtil.Export("Customers.xls", this.grdData);
DataTable dt = new DataTable();
// add the columns to the datatable
if (grdData.HeaderRow != null)
{
for (int i = 0; i < grdData.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(grdData.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in grdData.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.ToString();
}
dt.Rows.Add(dr);
}

Related

How to insert empty row at the top of data table in csv with C#?

I'm making a desktop application using the windows form with C#, I stored uploaded csv data with data grid view, then I make a transpose feature in the application, but did not work well, because the row of index or row 0 does not included in transpose output file.
Picture 1
So, I decided to add a empty row inside csv file at the top of data with this code
DataRow dr1 = dt.NewRow();
dt.Rows.InsertAt(dr1, 0);
I tried manually by insert empty row in csv and the application look like this
Picture 2
How should I code to make application insert an empty data row at 0 and store it in data grid view looks like a picture above? so my transpose feature works well
here I wrote to store the data in data grid
public DataSet ConnectCSV()
{
DataSet ds = new DataSet();
string fileName = openFileDialogCSVFilePath.FileName;
CsvReader reader = new CsvReader(fileName);
ds = reader.RowEnumerator;
dGridCSVdata.DataSource = ds;
dGridCSVdata.DataMember = "TheData";
return ds;
}
private void dGridCSVdata_Navigate(object sender, NavigateEventArgs ne)
{
}
here I wrote to read the data
public DataSet RowEnumerator
{
get
{
if (null == __reader)
throw new System.ApplicationException("I can't start reading without CSV input.");
__rowno = 0;
string sLine;
string sNextLine;
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("TheData");
DataRow dr1 = dt.NewRow();
dt.Rows.InsertAt(dr1, 0);
while (null != (sLine = __reader.ReadLine()))
{
while (rexRunOnLine.IsMatch(sLine) && null != (sNextLine = __reader.ReadLine()))
sLine += "\n" + sNextLine;
__rowno++;
DataRow dr = dt.NewRow();
string[] values = rexCsvSplitter.Split(sLine);
for (int i = 0; i < values.Length; i++)
{
values[i] = Csv.Unescape(values[i]);
if (__rowno == 1)
{
dt.Columns.Add(values[i].Trim());
}
else
{
if (Csv.CharNotAllowes(values[i]))
{
dr[i] = values[i].Trim();
}
}
}
if (__rowno != 1)
{
dt.Rows.Add(dr);
}
ds.Tables.Add(Transposer.Transpose(dt));
// transpose code
StringBuilder sb = new StringBuilder();
for (int u = 0; u < dt.Columns.Count; u++)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append(dt.Rows[i][u].ToString());
if (i < dt.Rows.Count - 1)
{
sb.Append(',');
}
}
sb.AppendLine();
}
File.WriteAllText("C:\\Users\\Desktop\\Output.csv", sb.ToString());
}
__reader.Close();
return ds;
}
}

c# dataGridView for loop to add data

Use a for loop to generate numbers, 1-100, and add each number to the dataGridView
After I tried with my code, I only showed one line, which is the last 100.
public void aaa(int i) {
DataTable dt = new DataTable();
dt.Columns.Add("host");
DataRow dr = dt.NewRow();
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e) {
for (int i = 1; i <= 254; i++)
{
aaa(i);
}
}
your btn_click function. Every loop will initialize or create a new object inside the aaa(i) function
Every time aaa(i) is called in the for loop DataTable dt = new DataTable() will be called
public void aaa(int i)
{
DataTable dt = new DataTable(); ///this will initialize every time, a new data table will be created every loop
dt.Columns.Add("host");
DataRow dr = dt.NewRow();
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
}
Might i suggest you pass the 254 int in your aaa(i) function and do the loop inside like
private void button1_Click(object sender, EventArgs e)
{
aaa(254);
}
public void aaa(int i) //value of i = 254
{
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
for (var s = 0; s <= i; s++ ) {
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
}
}
or if the reason for the loop in the button is just for the number limit in the loop inside void aaa then you can simplify it as
public void aaa(int i) //value of i = 254
{
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
}
I thought of the available solutions myself.
DataTable dt = new DataTable();
dt.Columns.Add("number");
int i = 10;
int a = 0;
while (a<=i)
{
DataRow dr = dt.NewRow();
a++;
dr[0] = a;
dt.Rows.Add(dr);
}
this.dataGridView1.DataSource = dt;
I always do this like that
ListCollectionView collectionView;
collectionView = new ListCollectionView(*your list of items*);
datagridView1.ItemSource = collectionView;
Implementing like this give you in future open way for sorting, filtering etc. Here is link to ms documentation. where you will find more information about listCollectionView.

how to export to excel with arabic problem

i'm not good in asking sorry
in my windows application , i have a gridview with data , Here i want to export gridview to excel ,I'm trying with below code
i have a problem with my code to export dataGridView to excel sheet i get the result like that (???%$^&$$&$%&$%^$#%##%##%)
i hope any one can help me with that code
i search about it many time and didn't found any answer
have no idea what collation the tables are set to. Is there a way to export the data correctly, or convert it to the correct encoding?
export button
private void Btexport_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
try
{
// Bind Grid Data to Datatable
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText, col.ValueType);
}
int count = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (count < dataGridView1.Rows.Count - 1)
{
dt.Rows.Add();
foreach (DataGridViewCell cell in row.Cells)
{
dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
}
}
count++;
}
// Bind table data to Stream Writer to export data to respective folder
StreamWriter wr = new StreamWriter(#"C:\Users\ils\Desktop\New folder (2)\Book1.xls");
// Write Columns to excel file
for (int i = 0; i < dt.Columns.Count; i++)
{
wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dt.Rows.Count); i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Rows[i][j] != null)
{
wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
wr.WriteLine();
}
wr.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
data
public void Disp_data()
{
SqlConnection mycon = new SqlConnection("Data Source=DESKTOP-J7D5POF;Initial Catalog=ilswork;Persist Security Info=True;User ID=test;Password=12345;Connect Timeout=60");
mycon.Open();
SqlCommand cmd = mycon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select name1 from [dbo].[test5]";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
mycon.Close();
}
private void Form3_Load(object sender, EventArgs e)
{
Disp_data();
}
}

How to add data continuity in DataTable?

I want to continue to add data to datatable that already contains data.
In this method, it was get data like: dt = { 1, 2 }.
public class GetRowOne()
{
// some code
if(contains == null)
{
DataRow dr = dt.NewRow();
string[] array1 = lstHeader[1].ToArray();
for (int i = 0; i < 8; i++)
dr[i] = array1[i];
}
// some code
}
dt.Rows.Add(dr.ItemArray);
Now, in another method, I also create and run same like this code.
public class GetRowTwoAndThree()
{
// some code
DataRow dr = dt.NewRow();
string[] array1 = lstHeader[1].ToArray();
for (int i = 0; i < 8; i++)
dr[i] = array1[i];
// some code
}
dt.Rows.Add(dr.ItemArray);
It return new values in dt is: dt = { 4, 5 }
I think error at like: DataRow dr = dt.NewRow(); or line: dt.Rows.Add(dr.ItemArray);
You will look: when dt.Rows.Add(dr.ItemArray). All before data will null, it only add new values to dt.
I want dt save old data and new data, it should be:
dt = { 1, 2, 3, 4 }
Store Data in ViewState["OldData"] and after adding new row again store dt in ViewState["OldData"].
If in same page you are calling method then store that in viewstate, you can also store in session or create get set method for that datatable
DataTable dt{get; set;}
EDIT-:
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
dt.Columns.Add("Column1");
dttest = dt;
}
public void GetRowOne()
{
DataRow dr = dt.NewRow();
dr["Column1"] = "Test";
dt.Rows.Add(dr);
dttest = dt;
}
DataTable dttest { get; set; }
private void button1_Click(object sender, EventArgs e)
{
GetRowOne();
}

I can't Add New Row after Deleting Row in Gridview ASP.net

I have a strange problem with my code
I can't add row because NullReferenceException in my gridview after delete a row.
My logic is when Add new row, i have the other function to SetPreviousData.
When I didn't delete a row, my SetPreviousData is don't raise any exception, but when after deleting a row and create new row, my SetPreviousData raise a exception that NullReferenceException.
This is my code for 'AddNewRow()'
private void AddNewRowToGrid()
{
if (ViewState["vsCurrent"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["vsCurrent"];
DataRow drNewRow = dtCurrentTable.NewRow();
drNewRow["SALES_SO_LITEM_ID"] = Convert.ToInt32(dtCurrentTable.Rows.Count.ToString()+"101");
drNewRow["ITEM_NAME"] = string.Empty;
drNewRow["QUANTITY"] = 0;
drNewRow["PRICE"] = 0;
dtCurrentTable.Rows.Add(drNewRow);
ViewState["vsCurrent"] = dtCurrentTable;
}
else
{
ViewState["vsCurrent"] = SetInitialRow();
}
BindDataGrid();
SetPreviousData(); //Set Previous Data on Postbacks
}
and this function for SetPreviousData
public void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["vsCurrent"] != null)
{
DataTable dt = (DataTable)ViewState["vsCurrent"];
if (dt.Rows.Count > 0)
{
int max_rowindex = gvDetailSales.Rows.Count - 1;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i].RowState != DataRowState.Deleted)
{
Label box1 = (Label)gvDetailSales.Rows[rowIndex].Cells[1].FindControl("lblItemName");
// raise exception because null
Label box2 = (Label)gvDetailSales.Rows[rowIndex].Cells[2].FindControl("lblQuantity");
Label box3 = (Label)gvDetailSales.Rows[rowIndex].Cells[3].FindControl("lblPrice");
box1.Text = dt.Rows[i]["ITEM_NAME"].ToString();
box2.Text = dt.Rows[i]["QUANTITY"].ToString();
box3.Text = dt.Rows[i]["PRICE"].ToString();
rowIndex++;
}
}
}
}
}
How I can handle it ? Thank You
======================EDITED================================================
This is my function for SetInitialRow
public DataTable SetInitialRow()
{
DataTable dtInitial = new DataTable();
DataRow drInitial = null;
dtInitial.Columns.Add(new DataColumn("SALES_SO_LITEM_ID", typeof(string)));
dtInitial.Columns.Add(new DataColumn("ITEM_NAME", typeof(string)));
dtInitial.Columns.Add(new DataColumn("QUANTITY", typeof(int)));
dtInitial.Columns.Add(new DataColumn("PRICE", typeof(float)));
drInitial = dtInitial.NewRow();
drInitial["SALES_SO_LITEM_ID"] = Convert.ToInt32(dtInitial.Rows.Count.ToString() + "101");
drInitial["ITEM_NAME"] = string.Empty;
drInitial["QUANTITY"] = 0;
drInitial["PRICE"] = 0.0;
dtInitial.Rows.Add(drInitial);
return dtInitial;
}
This is my function for BindDataGrid
public void BindDataGrid()
{
gvDetailSales.DataSource = ViewState["vsCurrent"] as DataTable;
gvDetailSales.DataBind();
}

Categories

Resources