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.
Related
so my problem is that I want to display a table inside another table in WPF.
I use a DataTable in order to display some data and there is one column, in which I need to display another DataTable. I set AutoGenerateColumns="True". For a little testing, this is what I wrote (well, it works as expected):
var curDataTable = new DataTable();
curDataTable.Columns.Add("name" , typeof(string));
curDataTable.Columns.Add("number", typeof(int));
DataRow curRowData = curDataTable.NewRow();
curRowData[0] = "jones";
curRowData[1] = 90;
curDataTable.Rows.Add(curRowData);
Now, let's say I already have a filled DataTable _dataTable. I now want to display this _dataTable in my second column. This is what i would expect to work, but what does not work:
var curDataTable = new DataTable();
curDataTable.Columns.Add("name" , typeof(string));
curDataTable.Columns.Add("table", typeof(DataTable));
DataRow curRowData = curDataTable.NewRow();
curRowData[0] = "jones";
curRowData[1] = _dataTable;
curDataTable.Rows.Add(curRowData);
Has anyone an idea how to fix this?
Using nested DataTables won't work.
What you should do is to replace the outer DataTable with a custom type and bind to a custom collection property of this type in a DataGridTemplateColumn.
I don't think that nested DataTables are possible...
What you can do is create new column in '_datatable' with the name of "name"
_datatable.Columns.Add("name" , typeof(string)).SetOrdinal(0);
Using SetOrdinal(0) you can make "name" column first column. Now you maybe able to add new columns to it.
I hope it helps
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";
I'm beginner in .Net ,so maybe my question will seem naive to some of you.
I have DataGridView table in WinForm project:
It contain three columns(image,combobox and textBox columns).
Any idea how to create and attach rows to this table?
Thank you in advance!
You create a data source, then bind the data source to the grid's DataSource property. You then add a record to your data source.
// create data source
BindingList<Shape> dataSource = new BindingList<Shape>();
// add record to data source
dataSource.Add(new Shape("Some Contour", "Circle", "Some Name"));
// bind data source
yourDataGridView.DataSource = typeof(BindingList<Shape>);
yourDataGridView.DataSource = dataSource;
Set the DataPropertyName of each column to matches the names of the fields in your Shape class.
DataGridViewTextBoxColumn colName = new DataGridViewTextBoxColumn();
colName.DataPropertyName = "Name";
yourDataGridView.Columns.Add(colName );
However, I recommend you use Virtual Mode instead to keep your data separate and decoupled.
If you wish to accept inputs from user, you have to create a form on this page using which the user can provide inputs. Take those values and add them to a DataTable. Following is a sample snippet showing it:
DataTable dt = new DataTable();
dt.Columns.Add("Contour",typeof(string)); //I am assuming that you will store path
//of image in the DataTable
dt.Columns.Add("Shape",typeof(string));
dt.Columns.Add("Name",typeof(string));
Keep adding new rows to the DataTable as you receive inputs from the user:
DataRow row = dt.NewRow();
row["Contour"] = txtContourPath.Text;
row["Shape"] = ddlShape.SelectedValue;
row["Name"] = txtName.Text;
dt.Rows.Add(row);
Assign above DataTable to DataSource property of the GridView.
dgv.DataSource = dt;
You can use method:
dataGridView1.Rows.Insert(...)
dataGridView1.Rows.Add(...)
Jay's answer : use dataGridView1.DataSource = dataSource;
Hope I can help you.
I have a DataGridView bound to a DataTable. The DataTable is populated from a database query. The table contains a column named BestBefore. BestBefore is a date formatted as a string (SQLite doesn't have date types).
I would like to programmatically add a new column to the DataGridView called Status. If BestBefore is less than the current date, Status value should be set to OK, otherwise Status value should be set to NOT OK.
I'm very new to Winforms, so some example code would be greatly appreciated.
UPDATE:
I think DataColumn.Expression is okay for doing simple calculations such multiplying a column's integer value by another value, but what about doing what I need to do? That is, calculate the difference between now and the date (string formatted) in the BestBefore column to determine what value to give the new status column. Example code would be appreciated.
Keep it simple
dataGridView1.Columns.Add("newColumnName", "Column Name in Text");
To add rows
dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]
Add new column to DataTable and use column Expression property to set your Status expression.
Here you can find good example: DataColumn.Expression Property
DataTable and DataColumn Expressions in ADO.NET - Calculated Columns
UPDATE
Code sample:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));
dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));
demoGridView.DataSource = dt;
UPDATE #2
dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
Here's a sample method that adds two extra columns programmatically to the grid view:
private void AddColumnsProgrammatically()
{
// I created these columns at function scope but if you want to access
// easily from other parts of your class, just move them to class scope.
// E.g. Declare them outside of the function...
var col3 = new DataGridViewTextBoxColumn();
var col4 = new DataGridViewCheckBoxColumn();
col3.HeaderText = "Column3";
col3.Name = "Column3";
col4.HeaderText = "Column4";
col4.Name = "Column4";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
}
A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)
For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:
// Note that this info scattered throughout the designer but can easily collected.
System.Windows.Forms.DataGridViewTextBoxColumn Column1;
System.Windows.Forms.DataGridViewCheckBoxColumn Column2;
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2});
this.Column1.HeaderText = "Column1";
this.Column1.Name = "Column1";
this.Column2.HeaderText = "Column2";
this.Column2.Name = "Column2";
I have a DataGridView and I am populating it through a DataTable. On initializing, I add DataColumns to the DataTable and then set the DataSource of the DataGridView to the DataTable. Here is the code:
DataTable mTable = new DataTable("Test");
DataColumn col = new DataColumn;
col.DataType = System.Type.GetType("System.Boolean");
col.ColumnName = "First";
col.ReadOnly = false;
mTable.Columns.Add(col);
col = new DataColumn;
col.DataType = System.Type.GetType("System.String");
col.ColumnName = "Second";
col.ReadOnly = false;
mTable.Columns.Add(col);
this.myGridView.DataSource = mTable;
This works fine however, I want to make one of the columns showup as a combobox. I think I have to do something with the Column's datatype but I am not sure how to do this. Can anyone give me any pointer towards this?
This is old, but I thought I'd try to answer it anyways since I had the same question myself a while ago.
First of all, you cannot make a DataTable column of type DataGridViewComboBoxColumn. DataColumn inherits from System.Data, while DataGridView*Columns inherit from System.Windows.Forms.
What you can try is this: Once your DataTable is bound to your DataGridView, the columns from the DataTable should show up on the DataGridView in the designer. If you then expand the Columns property of your DataGridView, you should see your columns from your DataTable have been added to the list. Select the column that you want, and in the right-hand pane there will be a property called 'ColumnType'. The default type is DataGridViewTextBoxColumn, but you can change it to DataGridViewComboBoxColumn.
change the declaration to this:
DataGridViewComboBoxColumn column1 = new DataGridViewComboBoxColumn()