I have made an identity column id with an auto-incremented equals true in datatable but it's empty.
Why ?
Datatable dt= new datatable();
DataColumn dc = new DataColumn("id", typeof(int));
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dt.Columns.Add(dc);
dc = new DataColumn("NITNo", typeof(string));
dc.DefaultValue = txtNitNo.Text.ToString();
dt.Columns.Add(dc);
dc = new DataColumn("WorkNo", typeof(string));
dc.DefaultValue = txtWorkNo.Text.ToString();
dt.Columns.Add(dc);
//dt.Rows.rem
//Bind Data to GridView
gvBOQ.Caption = Path.GetFileName(FilePath);
gvBOQ.DataSource = dt;
gvBOQ.DataBind();
If you add data to the DataTable, you have to make sure that the value in the Identity Column is null
//create a datatable
DataTable table = new DataTable();
//auto increment column
DataColumn column = new DataColumn("id", typeof(int));
column.AutoIncrement = true;
column.AutoIncrementSeed = 1;
column.AutoIncrementStep = 1;
table.Columns.Add(column);
//add a normal column
column = new DataColumn("value", typeof(string));
table.Columns.Add(column);
//add some data to the table
table.Rows.Add(null, "Netherlands");
table.Rows.Add(null, "Japan");
table.Rows.Add(99, "Australia");
table.Rows.Add(null, "America");
The resulting table will look like this
id value
1 Netherlands
2 Japan
99 Australia
100 America
You can loop through the datatable and increment the value of the particular column
e.g
int i = 1;
foreach (DataRow dr in table.Rows)
{
dr["id"] = i;
i++;
}
I already have the code that specify columns of the dataTable but what I want is to create a general method that has in her parameters: ColumnName and types.
How can I do that?
This is my code:
column = dt.Columns.Add();
column.ColumnName = "IPPName";
column.DataType = typeof(String);
column = dt.Columns.Add();
column.ColumnName = "tagName";
column.DataType = typeof(String);
column = dt.Columns.Add();
column.ColumnName = "time";
column.DataType = typeof(String);
column = dt.Columns.Add();
column.ColumnName = "value";
column.DataType = typeof(Double);
column = dt.Columns.Add();
column.ColumnName = "qtity";
column.DataType = typeof(Double);
I dont know if I understand question correctly. Do you want to implement something like this ?
public DataTable CreateDataTable(Dictionary<string,Type> columns)
{
DataTable dt = new DataTable();
foreach( var key in columns)
{
var column = dt.Columns.Add();
column.ColumnName = key.Key;
column.DataType = key.Value;
}
return dt;
}
public void CreateNewDataTable()
{
var columns = new Dictionary<string, Type>()
{
{"column", typeof (string)}
};
var dt = CreateDataTable(columns);
}
An additional way to solve it using extensionmethods. I believe it is a tad easier to follow than #adt answer and more useful since it can be called on an already existing DataTable.
If you need help regarding extensionmethods, have a look at this description or just ask :)
public static class DataTableExtentions {
public static void AddColumn(this DataTable table, string columnName, Type columnType)
{
var col = table.Columns.Add();
col.ColumnName = columnName;
col.DataType = columnType;
}
}
And it would be called like this:
column = dt.AddColumn("IPPName", typeof(String));
column = dt.AddColumn("tagName", typeof(String));
column = dt.AddColumn("time", typeof(String));
column = dt.AddColumn("value", typeof(Double));
column = dt.AddColumn("qtity", typeof(Double));
I cannot Display the value of "Price" cell on my gridview, here's my code:
DataColumn idCol2 = new DataColumn();
idCol2.DataType = System.Type.GetType("System.Int32");
idCol2.ColumnName = "Id";
table.Columns.Add(idCol2);
DataColumn SKUCol2 = new DataColumn();
SKUCol2.DataType = System.Type.GetType("System.String");
SKUCol2.ColumnName = "SKU";
table.Columns.Add(SKUCol2);
DataColumn ProdNameCol2 = new DataColumn();
ProdNameCol2.DataType = System.Type.GetType("System.String");
ProdNameCol2.ColumnName = "Product Name";
table.Columns.Add(ProdNameCol2);
DataColumn DescCol2 = new DataColumn();
DescCol2.DataType = System.Type.GetType("System.String");
DescCol2.ColumnName = "Product Description";
table.Columns.Add(DescCol2);
DataColumn PriceCol2 = new DataColumn();
PriceCol2.DataType = System.Type.GetType("System.Decimal");
PriceCol2.ColumnName = "Price";
table.Columns.Add(PriceCol2);
DataColumn[] keys2 = new DataColumn[5];
keys2[0] = idCol2;
table.PrimaryKey = keys2;
LivePOS livepos = new LivePOS(clientId, clientSecret);
_products = livepos.GetProducts(apiKey, token);
foreach (var p in _products)
{
table.Rows.Add(p.Id, p.Sku, p.Name, p.Description , p.SellingPrice);
}
table.DefaultView.Sort = "Id ASC";
dataGridView1.DataSource = table;
this.dataGridView1.DefaultCellStyle.Format = "N4";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells[0].ReadOnly = false; //id
row.Cells[1].ReadOnly = true; //sku
row.Cells[2].ReadOnly = true; //name
row.Cells[3].ReadOnly = true; //description
}
Please help me :)Is there something wrong in this code? I created new instance of the datatable named "table" on my Form_Load event. All cell values are displaying correctly aside from this "Price" column.
Your Price Column should have Datatype of Double than Decimal.Take a look at this link
Decimal Vs Double
hope that helps
I have a datagridview which I'm using for data entry. I've done this before with all text columns, and it worked great. But now I want one of the columns to be a databound combobox so the user can select options. When I do this, the resulting gridview's datasource ends up with empty rows (but the right quantity). What am I missing?
Here is code:
DataGridViewComboBoxColumn cboCategory = new DataGridViewComboBoxColumn();
{
cboCategory.HeaderText = "Category";
cboCategory.DataSource = downtimeCategories;
cboCategory.DisplayMember = "Name";
cboCategory.ValueMember = "CategoryID";
cboCategory.DataPropertyName = "CategoryID";
gridDowntime.Columns.Add(cboCategory);
}
Then code to grab gridview's datasource:
DataTable dt = (gridDowntime.DataSource as DataTable);
Everytime I get a table with the correct number of rows, but all the rows are empty (although they are long rows, the dataset visualizer has to scroll to show the entire cell). How can I find the error and correct?
EDIT: Is there some specific additional information I should provide here?
Here is a simple example project that I just cooked up.
The key thing I think you are getting wrong is that the DataPropertyName property of the DataGridViewComboboxColumn needs to refer to the datasource of the DataGridView, not the column.
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable("Customers");
DataColumn dc;
dc = new DataColumn();
dc.DataType = typeof(int);
dc.ColumnName = "CustomerID";
dt.Columns.Add(dc);
dt.Columns.Add(new DataColumn("LastName"));
dt.Columns.Add(new DataColumn("FirstName"));
// Concatenation of first and last names
dt.Columns.Add(new DataColumn("FullName"));
dt.Columns.Add(new DataColumn("Address"));
dt.Columns.Add(new DataColumn("City"));
dt.Columns.Add(new DataColumn("State"));
dt.Columns.Add(new DataColumn("Zip"));
dt.Columns.Add(new DataColumn("Phone"));
dc = new DataColumn();
dc.DataType = typeof(DateTime);
dc.ColumnName = "LastPurchaseDate";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = typeof(int);
dc.ColumnName = "CustomerType";
dt.Columns.Add(dc);
// Populate the table
dt.Rows.Add(2, "Baggins", "Bilbo", "Baggins, Bilbo", "Bagshot Row #1", "Hobbiton", "SH", "00001", "555-2222", DateTime.Parse("24/9/2008"), 1);
dt.Rows.Add(1, "Baggins", "Frodo", "Baggins, Frodo", "Bagshot Row #2", "Hobbiton", "SH", "00001", "555-1111", DateTime.Parse("14/9/2008"), 1);
dt.Rows.Add(6, "Bolger", "Fatty", "Bolger, Fatty", "ProudFeet Creek", "Hobbiton", "SH", "00001", "555-1111", DateTime.Parse("14/9/2008"), 1);
dt.Rows.Add(4, "Elessar", "Aragorn", "Elessar, Aragorn", "Citadel", "Minas Tirith", "Gondor", "00000", "555-0000", DateTime.Parse("14/9/2008"), 4);
dt.Rows.Add(5, "Evenstar", "Arwin", "Evenstar, Arwin", "Citadel", "Minas Tirith", "Gondor", "00000", "555-0001", DateTime.Parse("23/9/2008"), 4);
dt.Rows.Add(3, "Greyhame", "Gandalf", "Grayhame, Gandalf", DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, 3);
DataGridViewComboBoxColumn cboCategory = new DataGridViewComboBoxColumn();
List<CustomerType> customerTypes = new List<CustomerType> { new CustomerType { Id = 1, Name = "Good" }, new CustomerType { Id = 4, Name = "Bad" }, new CustomerType { Id = 3, Name = "Ugly" } };
cboCategory.HeaderText = "Customer Type";
cboCategory.DataSource = customerTypes;
cboCategory.DisplayMember = "Name";
cboCategory.ValueMember = "Id";
cboCategory.DataPropertyName = "CustomerType";
dataGridView1.Columns.Add(cboCategory);
dataGridView1.DataSource = dt;
}
Bit of fluff in there - grabbed that datatable code right off the interwebs. But the key part here is the setting of properties for the combobox column.
My datasource is a list of customertype objects:
public class CustomerType
{
public int Id { get; set; }
public string Name { get; set; }
}
So I need to set DisplayMember on the column to "Name" and ValueMember to "Id" since this references the columns datasource. However for the DataPropertyName was set the value to "CustomerType" which is the name of a column in the DataTable that we have bound to the DataGridView.
So after a wee bit of discussion in chat it turns out that the above is true but that you also need to ensure that the types of your id columns match.
The datatable used to provide data to the combobox column was generated from a sql query and had the id column of type in. Your backing datatable had the id column made like so:
dt.Columns.Add(new DataColumn("Category"));
This defaults to a column of type string. Try instead something like:
downtimeEntries.Columns.Add("Category", typeof(int));
Current Code:
foreach (Expressions e in expressionObj)
{
if ((e.Expression != null) && (e.ColumnName != null))
{
newtable1.Columns.Add(new DataColumn(e.ColumnName, typeof(decimal), e.Expression));
}
}
I have an expression as ID+ID which is to be added as new column in the datatable as SUM-ID where ID=2, but the result got is 22 instead of 4.
Let's see:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(decimal)));
dt.Columns.Add(new DataColumn("SUM-ID", typeof(decimal), "ID + ID"));
var row = dt.NewRow();
row["ID"] = 2;
dt.Rows.Add(row);
var val = dt.Rows[0]["SUM-ID"];
Result: val is 4 as expected.
Let's try something else:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(string)));
dt.Columns.Add(new DataColumn("SUM-ID", typeof(decimal), "ID + ID"));
var row = dt.NewRow();
row["ID"] = "2";
dt.Rows.Add(row);
var val = dt.Rows[0]["SUM-ID"];
Result: val is 22
Conclusion: Your ID column is of type string but it needs to be a numeric type instead otherwise string concatenation is used.
Update: If you cannot (or don't want to) set the datatype of the column then you can use Convert inside the expression: 2 * Convert(ID, 'System.Int32')