Bug in C#?

E

Eddie B.

I am trying to create a new row with the values from textboxes. When I
create the first row it works fine but when I click the button to create
another row it only overwrites the existing row. this is what I am doing.
Toward the bottom (about 8 uncommented lines from
bottom) where DataRow first appears is where my trouble starts.
//Create DataSet

DataSet ds = new DataSet();

//Create DataTable

DataTable dt = new DataTable("Meds");

//Add DataTable to DataSet

ds.Tables.Add(dt);

//Add Columns to DataTable

DataColumn dc = new DataColumn("Drug");

ds.Tables["Meds"].Columns.Add(dc);

DataColumn dc2 = new DataColumn("Dose");

ds.Tables["Meds"].Columns.Add(dc2);

DataColumn dc3 = new DataColumn("Form");

ds.Tables["Meds"].Columns.Add(dc3);

DataColumn dc4 = new DataColumn("Route");

ds.Tables["Meds"].Columns.Add(dc4);

DataColumn dc5 = new DataColumn("Frequency");

ds.Tables["Meds"].Columns.Add(dc5);

DataRow tr = dt.NewRow();

tr["Drug"] = this.textBox11.Text;

tr["Dose"] = this.textBox12.Text;

tr["Form"] = this.textBox13.Text;

tr["Route"] = this.textBox14.Text;

tr["Frequency"] = this.textBox15.Text;


//Add rows to data table

dt.Rows.Add(tr);


//Display in dataGrid

this.dataGrid3.DataSource = dt;
 
G

Guest

Your code as shown will recreate a new DataSet , dataTabel and a row each time you click a button if your code is as show

You need to
1. define the dataset and DataTable at the form level
2. Then intialization then in form load or intilializatino or on a seperate button.
3. On your row add button create the datarow and add it to the EXISTING data table vs Creating it as you are now.

I
public your form: For

........et

//Define: Your dataSet, DataTable at the form leve
private DataSet ds
//Create DataTabl
private DataTable dt

form_Load or form() //Load or Initialize..

//Create DataSe
ds = new DataSet()
//Create DataTabl
dt = new DataTable("Meds")
//Add DataTable to DataSe
ds.Tables.Add(dt)
//Add Columns to DataTabl
DataColumn dc = new DataColumn("Drug")
ds.Tables["Meds"].Columns.Add(dc)
DataColumn dc2 = new DataColumn("Dose")
ds.Tables["Meds"].Columns.Add(dc2)
DataColumn dc3 = new DataColumn("Form")
ds.Tables["Meds"].Columns.Add(dc3)
DataColumn dc4 = new DataColumn("Route")
ds.Tables["Meds"].Columns.Add(dc4)
DataColumn dc5 = new DataColumn("Frequency")
ds.Tables["Meds"].Columns.Add(dc5)


YOURBUTTONCLIC

DataRow tr = dt.NewRow()
tr["Drug"] = this.textBox11.Text
tr["Dose"] = this.textBox12.Text
tr["Form"] = this.textBox13.Text
tr["Route"] = this.textBox14.Text
tr["Frequency"] = this.textBox15.Text

//Note because it is defined at the class level you can access it here in your button click.
//Add rows to data tabl
dt.Rows.Add(tr)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top