paraJdox1
paraJdox1

Reputation: 973

How to add a value in the cells of a specific column in a datagridview in c#.net?

This is what my datagridview looks like:

enter image description here

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

Answers (1)

v m
v m

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

Related Questions