Reputation: 973
This is what my datagridview looks like:
The values Name, Price, Total, and Quantity column is loaded from a database. I want to add an initial value zero(0) to the "Item/s Added or Subtracted" column.
This is how I populate my datagridview:
con.Open();
DataTable dt = new DataTable();
SqlCommand cm = new SqlCommand("SELECT * FROM Stock");
cm.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cm);
da.Fill(dt);
stockGridView.AutoGenerateColumns = false;
stockGridView.Columns[0].DataPropertyName = "Name";
stockGridView.Columns[1].DataPropertyName = "Price";
stockGridView.Columns[2].DataPropertyName = "Total";
stockGridView.Columns[3].DataPropertyName = "Quantity";
stockGridView.DataSource = dt;
con.Close();
My + and - column are now working and can now increment/decrement by 1, and the incremented/decremented value can be displayed in the "Item/s Added or Subtracted" column, but it will be better if I can put an initial value there.
I have tried this:
DataTable dt = new DataTable();
DataColumn newColumn = new DataColumn("addOrSubtractItem", typeof(String));
newColumn.DefaultValue = 0;
dt.Columns.Add(newColumn);
but it doesn't display the 0
I also tried: reference -> https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/unbound-column-to-a-data-bound-datagridview?view=netframeworkdesktop-4.8
DataGridViewTextBoxColumn buttonColumn = new DataGridViewTextBoxColumn();
buttonColumn.Name = "Item/s Added or Subtracted";
buttonColumn.HeaderText = "Item/s Added or Subtracted";
stockGridView.Columns.Insert(4, buttonColumn);
but I cant put the 0 value in the cells.
Upvotes: 0
Views: 1329
Reputation: 195
You do it basically well, but not completely. After fill datatable from DB you add new column to datatable and set all rows to "0" value. Then you set DataTable as datasource of GridView.
Program code example:
con.Open();
DataTable dt = new DataTable();
SqlCommand cm = new SqlCommand("SELECT * FROM Stock");
cm.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cm);
da.Fill(dt);
con.Close();
//add new column to Datatable
dt.Columns.Add("addOrSubtractItem", typeof(int));
foreach (DataRow dr in dt.Rows)
{
dr["addOrSubtractItem"] = 0;
}
stockGridView.AutoGenerateColumns = false;
stockGridView.Columns[0].DataPropertyName = "Name";
stockGridView.Columns[1].DataPropertyName = "Price";
stockGridView.Columns[2].DataPropertyName = "Total";
stockGridView.Columns[3].DataPropertyName = "Quantity";
stockGridView.Columns[4].DataPropertyName = "addOrSubtractItem";
stockGridView.DataSource = dt;
Upvotes: 1