I have to export data to excel sheet in asp.net c# application. Now I have wriiten below lines of code
DataTable dt = new DataTable();
dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
row["ExpiryDate"] = Convert.ToDateTime(row["ExpiryDate"]).ToShortDateString();
}
DataSet dsn = new DataSet();
DataTable dtcopy = dt.Clone();
dsn.Tables.Add(dtcopy);
WebUtility.GenrateExcel(ds, "ExpiredDocuments");
I want to first remove time from data set's Expiry date column and then pass
it to the generate Excel function so that time will not appear in Expiry date column in excel... Please help the above code is not working...
I guess, you need look through this:
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
You should use smth like
Convert.ToDateTime(ds.Tables[0].Rows[i]["ExpiryDate"]).ToString("MM/dd/yyyy")
Or whatever you need.
These are the steps you need to do in order to accomplish what you are asking:
Create a new column of type string
Set the new column's value to ShortDateString of the corresponding "ExpiryDate" column
Remove the "ExpiryDate" column
Move the new string column to the position of the old "ExpiryDate" column
Rename the new column to "ExpiryDate"
Like so:
dt.Columns.Add("ExpiryDateString", typeof(String));
foreach(DataRow row in dt.Rows)
{
row["ExpiryDateString"] = ((DateTime)row["ExpiryDate"]).ToShortDateString();
}
int columnNumber = dt.Columns["ExpiryDate"].Ordinal;
dt.Columns.Remove("ExpiryDate");
dt.Columns["ExpiryDateString"].SetOrdinal(columnNumber);
dt.Columns["ExpiryDateString"].ColumnName = "ExpiryDate";
Related
I have a dataset in c# visual studio. I have one of column values of the one of the rows. I need to select that row using that value and store it in a datarow so that I can delete it. So how can I get the row of the datatable from one of the column values. I was trying something like this:
DataRow rowtobeselected = TableName["SerialNumber = 156"];
But as you know this is wrong. Also I need to get another colum value
from this row. For eg I need to get the value from the column date.
string Date = rowtobeselected.date;
I want to do something like this. So how to do it correctly. Thank you.
DataTables support a SQL like Select syntax:
https://learn.microsoft.com/en-us/dotnet/api/system.data.datatable.select?view=net-5.0
DataRowView row = (DataRowView)OtherTable.SelectedItem;
string serialnumbr = row.Row["SerialNumber"].ToString();
DataRow[] result = TableName.Select("SerialNumber =" + serialNumbr);
DataRow dr = result.FirstOrDefault();
if (dr != null)
{
DateTime dt = DateTime.Parse(dr["Date"].ToString());
}
I have a datatable filled with a report from a web service. I am now trying to display the datatable in an datagridview. This is the code I use to build the datatable:
// Create DataTabe to handle the output
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("EmployeeFirstName");
dt.Columns.Add("EmployeeLastName");
dt.Columns.Add("DepartmentName");
dt.Columns.Add("DepartmentCode");
dt.Columns.Add("LocationName");
dt.Columns.Add("DivisionCode");
dt.Columns.Add("EarningName");
dt.Columns.Add("OTHours");
dt.Columns.Add("WorkDate")
Fill the new datatable:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(string.Join(",", row.ColumnValues));
}
Then I try to bind the data in the datatable to the dataGridview:
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
When I run the application it only displays the data from the first column in the datatable. Do I need a loop of sorts to work through the columns or am I just missing a step?
Yes that's cause you are adding only one value to your dt when you say dt.Rows.Add(string.Join(",", row.ColumnValues));. You should be doing something like below (assuming that ReportRow also has the columns with same names like "EmployeeFirstName" else change the names accordingly)
foreach (ReportRow row in report.Rows)
{
DataRow dr = dt.NewRow();
dr["EmployeeFirstName"] = row["EmployeeFirstName"];
dr["EmployeeLastName"] = row["EmployeeLastName"];
dr["DepartmentName"] = row["DepartmentName"];
//rest of the columns fill
//once all columns filled
dt.Rows.Add(dr);
}
dt.Rows.Add(string.Join(",", row.ColumnValues)); -> You can either add a single DataRow item or a array of objects.
From your call, you chose the later, you are adding a array of objects, except you are adding ONE SINGLE object.
string.Join(",", row.ColumnValues) is one object.
Well after sleeping I have found the issue with dropping it into an sql table... I didn't take into account that the export to a CSV and the addition of the " , " would affect the export to sql. Here is the modification of the lines of code that was the issue:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(row.ColumnValues);
}
Thank you all for your responses!
I have a DataTable that I'm exporting to pdf and there are numeric value like status id that I want to change to strings for example:
dataRow["statusId"] = 1; //dataRow["statusId"] type is int
and I want it to be:
dataRow["statusId"] = "Open file";
How can I do it without coping the entire data table ?
You actually can't do it. The best way is to actually clone the dataTable and then copy each row:
DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32); //in the column you actually need.
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
Source: How To Change DataType of a DataColumn in a DataTable?
DataTable dt = new DataTable();
var dr = dt1.Date;
String rr = Convert.ToString(dr);
DataColumn dc1=new DataColumn();
dc1.ColumnName = rr; dt.Columns.Add(dc1);
And if i add datarow after this like
dt.Rows.Add("hello","hello1","hello2");
dataGrid1.ItemsSource = dt.DefaultView;
the data is not displayed in the grid .
If i comment the line
dc1.ColumnName = rr;
the values are displayed properly
But i want the colmn name to be the date that is "dt1" here
pleae note that the dt1 are the date values which is dynamic and it will be incremented in each loop.
like
dt1 = dt1.AddDays(1);
Please help
Without seeing your Xaml for the data grid it's difficult to be sure but I imagine that you've specified a field name for the date column in your xaml.
To resolve this, you'll need to set AutoGenerateColumns=True and let the grid automatically find the field name.
How do I add a new DataColumn to a DataTable object that already contains data?
PseudoCode
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", type(System.Int32));
foreach(DataRow row in dr.Rows)
{
//need to set value to NewColumn column
}
Just keep going with your code - you're on the right track:
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", typeof(System.Int32));
foreach(DataRow row in dt.Rows)
{
//need to set value to NewColumn column
row["NewColumn"] = 0; // or set it to some other value
}
// possibly save your Dataset here, after setting all the new values
Should it not be foreach instead of for!?
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("MyRow", **typeof**(System.Int32));
foreach(DataRow dr in dt.Rows)
{
//need to set value to MyRow column
dr["MyRow"] = 0; // or set it to some other value
}
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)
dt.Columns.Add("MyRow", typeof(System.Int32));
dt.Columns["MyRow"].Expression = "'0'";
Try this
> dt.columns.Add("ColumnName", typeof(Give the type you want));
> dt.Rows[give the row no like or or any no]["Column name in which you want to add data"] = Value;