Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically adding rows to a datgrid view

Status
Not open for further replies.

ggeorgiou01

Programmer
Apr 11, 2005
60
GB
Hi all,

I have a windows application and a couple of text entry textboxes, which once filled in, and the button has been clicked, will enter a row into a datagrid.... this works fine (see code)

if (this.CustomerInfoUc.OrderLinesDg.Rows.Count == 0)
{
DataTable dt = new DataTable("test");
DataColumn dc = new DataColumn();
DataRow dr;

dc = new DataColumn();
dc.DataType = Type.GetType("System.Int32");
dc.ColumnName = "Line";
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = Type.GetType("System.String");
dc.ColumnName = "Code";
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = Type.GetType("System.String");
dc.ColumnName = "Description";
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = Type.GetType("System.String");
dc.ColumnName = "ExpCode";
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = Type.GetType("System.Int32");
dc.ColumnName = "Qty";
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = Type.GetType("System.String");
dc.ColumnName = "Unit";
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = Type.GetType("System.Decimal");
dc.ColumnName = "Price";
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = Type.GetType("System.Decimal");
dc.ColumnName = "Total";
dt.Columns.Add(dc);

dr = dt.NewRow();
dr["Code"] = CodeTb.Text;
dr["Description"] = DescriptionTb.Text;
dr["ExpCode"] = ExpCodeTb.Text;
dr["Qty"] = QtyTb.Text;
dr["Unit"] = UnitTb.Text;
dr["Price"] = PriceTb.Text;
dr["Total"] = TotalPriceTb.Text;
dt.Rows.Add(dr);

this.CustomerInfoUc.OrderLinesDg.DataSource = dt;
StatusLb.Text = "Order line added";

ClearDataGridTextFields();
}
else
{

}

But when i enter some more data into my textboxes and click the button, instead of adding a new row to the datagrid, it overwrites the first row....

How do i go about adding a row, beneath my already added row ?
 
I think the problem is here:

if (this.CustomerInfoUc.OrderLinesDg.Rows.Count == 0)
{
DataTable dt = new DataTable("test");

You're creating the datatable everytime this condition validates true, so you're only ever going to see one row of the new datatable.

To remedy this, declare your datatable and datacolumns just once at the start of your function / class and then write to it when you click your button.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top