I'm using the table adapter in C# where I created a DataGridView. When I double click a row, I am displaying all the cells in the row in textboxes in a different Form. After I edit the textboxes and click my save button, I would like to take the values from the textboxes and replace them in the database. I can see the changes on the DataGrid, however I am not able to save them in the database.
private void InventoryData_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//make new form and display them there
ViewInventoryItem ViewItem = new ViewInventoryItem();
ViewItem.textBox1.Text = this.InventoryData.CurrentRow.Cells[1].Value.ToString();
ViewItem.textBox2.Text = this.InventoryData.CurrentRow.Cells[2].Value.ToString();
ViewItem.textBox3.Text = this.InventoryData.CurrentRow.Cells[3].Value.ToString();
ViewItem.ShowDialog();
if (ViewItem.DialogResult == DialogResult.OK)
{
//save button was pressed
this.InventoryData.CurrentRow.Cells[0].Value = ViewItem.textBox1.Text;
this.InventoryData.CurrentRow.Cells[1].Value = ViewItem.textBox2.Text;
this.InventoryData.CurrentRow.Cells[2].Value = ViewItem.textBox3.Text;
this.Validate();
this.InventoryData.EndEdit();
this.booksTableAdapter.Update(this.InventoryDataSet.Books);
}
}
Found the problem. In the Dataset the Table had only Fill and Get Data. Even after selecting the Wizard to add the other statements it was failing. After adding the UpdateQuery manually, the code works without issues. Thank you Crowcoder for pointing me in the right direction.
Related
I'm trying to use a datagridview for displaying several different tables data upon a radio click event. My problem is that the table adapter is not showing up but when I check the .xsd file, it say it is there, but in the design it is not and I'm unsure of what to do to get it to show there. Here is my code:
private void QBC_CM_Form_Load(object sender, EventArgs e)
{
// fill the form with the users on form load
this.usersTableAdapter.Fill(this.qbc_clothing_ministryDS.users);
}
private void radioBtnUserReports_CheckedChanged(object sender, EventArgs e)
{
// since user reports was selected
// bind the datasource to this.usersBindingSource (bound to users table)
dgvReports.DataSource = this.usersBindingSource;
// rename the header text visible (so it's not the database column names)
dgvReports.Columns[0].HeaderText = "ID";
dgvReports.Columns[1].HeaderText = "First Name";
dgvReports.Columns[2].HeaderText = "Last Name";
dgvReports.Columns[3].HeaderText = "Address";
dgvReports.Columns[4].HeaderText = "Phone";
dgvReports.Columns[5].HeaderText = "Cell";
dgvReports.Columns[6].HeaderText = "Email";
}
private void radioBtnClothingReports_CheckedChanged(object sender, EventArgs e)
{
// since the clothing reports was selected
// bind the datasource to this.qbc_clothing_ministryDataSet1.clothing_reports (clothing reports table)
this.qbcClothingReportsBindingSource.DataSource = this.qbc_clothing_ministryDataSet1.clothing_reports;
dgvReports.DataSource = this.qbcClothingReportsBindingSource;
// rename the header text visible (so it's not the database column names)
dgvReports.Columns[0].HeaderText = "ID";
dgvReports.Columns[1].HeaderText = "Name";
dgvReports.Columns[2].HeaderText = "Clothing Taken";
dgvReports.Columns[3].HeaderText = "Month";
dgvReports.Columns[4].HeaderText = "Year";
// why is this data from the db not showing up?
}
Here are some screenshots that also will help explain (hopefully)
.xsd file:
form design file:
program running -
and finally the data in the database (mssql server) -
I know if I could reference the table adapter, I think I could load the data but it's not showing up (like usersTableAdapter).
Any help would be appreciated
Thanks!
Try going to the project tab in Visual Studio (VS) and click the Add New Data Source... option. A window will pop-up choose the Database option and click [Next>]. Then click Dataset and again click [Next>]. This will bring up the data connection settings. Create a New Connection by clicking the [New Connection...] button. This will allow you to add a connection. Enter your server name in the server name text box. You can then enter the details on login in the Log on to server section of this window. Once you do those things click the [Test Connection] button and you should be all good. If that does not work then make sure you entered all the correct info on this window.
If its all good click [Ok] on that window and then click [Next>], a window will check boxes should appear. Under tables selected all the ones you want to use. Then click [Finish].
Now you should be able to use the table adapters for the data tables in the database, for example:
var myTableAdapter = new nameYouGaveDataSetTableAdapters.youTableTableAdapter();
System.Data.DataTable dt = myTableAdapter.GetData();
this will load in the data to the data table dt."nameYouGaveDataSetTableAdapters" is default named as yourDataBaseTableAdapters.
I have a dataGridVew1 on my windows form that I am populating from SQL using SQL Adapter named in my case "sda".
You can see how I update my grid below (maybe I am doing something wrong):
SqlConnection con = new SqlConnection("connection string"); //defining connection
con.Open();
string sql_command = "Select * from Test_Table";
SqlCommand command = new SqlCommand(sql_command, con); // defining the command
DataSet set = new DataSet("SQL_table");
SqlDataAdaptersda = new SqlDataAdapter(command); //defining the adapter and make it accept changes
sda.AcceptChangesDuringFill = true;
sda.AcceptChangesDuringUpdate = true;
set.Clear(); //just to make sure my adapter is empty
cmdBuilder = new SqlCommandBuilder(sda); //creating the command builder so I can save the changes
sda.Fill(set, "SQL_table"); // fill the dataset
dataGridView1.DataSource = set;
dataGridView1.DataMember = "SQL_table"; //fill datagrid
dataGridView1.CellValueChanged -= dataGridView1_CellValueChanged;
dataGridView1.CellValueChanged += dataGridView1_CellValueChanged; //look for cell value changed (I am using this in other scope)
When I manually change a value to any cell of the grid I use a button to save the changes to the database using:
private void button2_Click(object sender, EventArgs e)
{
sda.Update(set.Tables["SQL_table"]);
}
It works perfectly.
I have added a second button to change a cell value in the datagrid for the selected row, but I have trouble saving those changes.
private void button3_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0) //I am checking to see if any row is selected
{
row_index = this.dataGridView1.SelectedRows[0].Index; //to get the selected row index
this.dataGridView1.Rows[row_index].Cells[2].Value = "change"; //I am changing the cell text on column 2 on the selected row
dataGridView1.EndEdit(); //added this to try an make it work
sda.Update(set.Tables["SQL_table"]); //trying to update the database
}
else
MessageBox.Show("Please first select the row with the quote that is awaiting feedback."); // in case no row is selected
}
This does not save the data to the database. I also tried pressing the other save button afterward but no result, no data is saved in the database even if the value "changed" is visible in the grid.
I know I cannot put the save command in the CellValueChanged event because it does not take the last change.
How can I make it work in a separate button as mentioned above? What I need is to:
1. Press the button - that changes the value of a cell
2. commit the changes in the database.
Thank you.
Danut
EDIT 1: on Bolu's request
I am using the CellValueChanged event to update a column in my datagrid when other cells are changed:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex > -1 && e.ColumnIndex < 13)
{
DateTime datetime_send = DateTime.Now;
dataGridView1.Rows[e.RowIndex].Cells[13].Value = datetime_send;
}
}
I tried putting the update in the event but it does not save, so I am using the separate button to call the database save. (but this is another story). Now I just want to save the changes that i do with button3, which is update one cells value and then save in the database.
For a windows application, I have a form with a gridview. In the form, I have an Edit button. If the user selects one row and clicks on Edit, it has to redirect to another form with the selected data. The user can then enter details in that. When the user clicks on Save Data, it should save and go back to the database.
FIRSTListForm
private void btnNewFIRSTList_ItemClick(object sender, ItemClickEventArgs e)`
{
FIRSTEditForm FIRSTEditForm = new FIRSTEditForm(FIRSTID);`
FIRSTEditForm.Show();
}
private void btnEditFIRSTList_ItemClick(object sender, ItemClickEventArgs e)
{
//I need to know which row I selected before to Edit button
//object IdFirst = ((GridView)sender).GetRowCellValue(e.RowHandle, "IDFIRST");
//I need like a GetRowCellValue
FIRSTEditForm.Show();
}
You need a save method to write your data back to your database and call it on your save button click
Here is multiple examples of exactly what your wanting
if you want to open a separate form then youll need something like This
If you're using Datasets with winforms you can try:
1)Check if your gridview has any selected rows first
if (gridView1.SelectedRowsCount > 0)
{
......
}
2) If that's the case using strongly named DataRow class and BindingSource.Current:
YoutDataSet.YourTableOrResultSetRow Row;
var P = YourTableOrResultSetBindingSource.Current as DataRowView;
Row = (P.Row as YoutDataSet.YourTableOrResultSetRow );
int id = Row.ColumnNameThatContainstheID; //this will give you the ID you're after
Try it sir,
private void gridView_DoubleClick(object sender, EventArgs e)
{
if (gridView.GetFocusedRow() == null) return;
if (gridView.GetFocusedRowCellValue("ID") == null) return;
string id = gridView.GetFocusedRowCellValue("ID").ToString();
FIRSTEditForm frm = new FIRSTEditForm(id);
frm.Show();
}
In FIRSTEditForm use got ID and bind all your controls and save to database.
I use gridView_DoubleClick instead of your btnEditFIRSTList_ItemClick.
Hope it solves!
I have binded datagridview with datatable (Growns). My main goal is, that user can work with datagridview (dataGridView1), filling and updating data and when button SAVE is clicked, all data would be saved into datatable, because I need it for further work.
Everything works fine, exept saving data into datatable. What am I doing wrong?
Here is my code:
private void Form2_Load(object sender, EventArgs e) {
// TODO: This line of code loads data into the 'tekmovalecDataSet.Odrasli' table. You can move, or remove it, as needed.
this.grownsTableAdapter.Fill(this.competitorDataSet.Odrasli);
}
private void buttonSave_Click(object sender, EventArgs e) {
if (EmptySpace())
{
CompetitorDataSet.OdrasliRow newGrownsRow = competitorDataSet.Growns.NewGrownsRow();
newGrownsRow.StN = textStN.Text;
newGrownsRow.Name = textN.Text;
newGrownsRow.Surname = textSN.Text;
newGrownsRow.Club = textC.Text;
newGrownsRow.YBirth = textYB.Text;
competitorDataSet.Growns.Rows.Add(OdrasliNova);
competitorDataSet.Growns.AcceptChanges();
this.dataGridView1.DataSource = competitorDataSet.Growns;
this.Validate();
this.grownsBindingSource.EndEdit();
if (dataGridView1.BindingContext[competitorDataSet.Growns] != null)
{
dataGridView1.BindingContext[competitorDataSet.Growns].EndCurrentEdit();
}
this.grownsTableAdapter.Update(competitorDataSet.Odrasli);
this.grownsTableAdapter.Adapter.AcceptChangesDuringUpdate = true;
}
else
{
MessageBox.Show("Fill ALL data about competitor!");
}
}
P.S.: When I manually fill datatable, on form open datagridview is filled, so datatable and datagridview are connected I suppose...
P.S.2.: bool EmptySpace works fine.
When you set this.Update(competitorDataSet.Odrasli); the TableAdapter updates the changes from DataTable (news, deleted, updated rows) to the database.
Since you call competitorDataSet.Growns.AcceptChanges(); before TableAdapter.Update, all changes in the table are already accepted and TableAdapter has nothing to update.
So just remove
competitorDataSet.Growns.AcceptChanges();
Also, if you set this.grownsTableAdapter.Adapter.AcceptChangesDuringUpdate = true before grownsTableAdapter.Update(competitorDataSet.Odrasli);, the changes will be accepted and so you don't need to accept changes yourself (and it seems to me that default value is True so I am not sure this line is required)
You are not editing the data with the datagridview, you are changing the dataset using the textboxes, I think this is your example with the manual fill...
I will presume that the code you want to use to update the database begins at this line:
this.dataGridView1.DataSource = competitorDataSet.Growns;
I suspect your problem is in the following code block (explanations in code comments):
//why rebind the datagridview?
//this line should be removed
this.dataGridView1.DataSource = competitorDataSet.Growns;
//why call this here? validation should be done prior
//to adding the new row to the datatable
//this line should be removed
this.Validate();
this.grownsBindingSource.EndEdit();
if (dataGridView1.BindingContext[competitorDataSet.Growns] != null)
{
dataGridView1.BindingContext[competitorDataSet.Growns].EndCurrentEdit();
}
//reverse the order of these 2 lines
this.grownsTableAdapter.Update(competitorDataSet.Odrasli);
this.grownsTableAdapter.Adapter.AcceptChangesDuringUpdate = true;
/* like this:
this.grownsTableAdapter.Adapter.AcceptChangesDuringUpdate = true;
this.grownsTableAdapter.Update(competitorDataSet.Odrasli);
*/
If this does not solve your problem, please post the binding code for your datagriview.
I have a dataset, and 2 datatables.
Datatable1 = Combobox source (This will display a list of options)
Datatable2 = DataGrid (This will display data relevant to the options in combo box)
Submit Button (populate datagrid based on combo box selected value)
When i select an item in combo box and click submit, it load up the relevant records in datagrid. If i then change a value in the datagrid and click the submit button, the value i have just changed, dissapears?
How can i make it so that any altered datagrid values amend the datable, so that even if i view different options, i can always return any, an retain any of the changed values?
Here is my code:
//Load the data grid according to the ComboCAtegory selection
public void Grid_Load()
{
DataSet();
var Result = from c in DataSet_Main.Tables[2].AsEnumerable()
where c.Field<string>("Test_Code").Equals(comboBox_CategorySelect.SelectedValue)
select c;
dataGridView_Main.DataSource = Result.AsDataView();
dataGridView_Main.Columns["Test_Code"].Visible = false;
dataGridView_Main.Columns["ID"].Visible = false;
dataGridView_Main.Columns["Description"].Visible = false;
dataGridView_Main.Columns["Expected_Result"].Visible = false;
}
private void buttonSubmit_Click(object sender, EventArgs e)
{
Grid_Load();
}
public void Fail()
{
DataTable dt = DataSet_Main.Tables[2];
//dataGridView_Main.SelectedRows[0].Cells["Check"].Value = "Fail";
dt.Rows[dataGridView_Main.SelectedRows[0].Index]["Check"] = "Fail";
}
private void buttonFail_Click(object sender, EventArgs e)
{
Fail();
}
Hope this makes sense?
I think your DataGrid is already bound to the Data Table. What you need to do is send the changes back to the data source so that they would be reflected in the second data table which is bound to the same data source. To do this, write an event handler for CellChanging event on the DataGrid and in that you can the call Update() method on your Data Adapter (if you are using one, that is) to send changes to the data source. Then, in the same event handler, update the items in the combo box by refreshing the data bind so that the combo box gets latest values from the second data table.
This way, whenever the cell changes its value in the DataGrid, you can check if it is the relevant cell which you want and update the combo box based on the changes in the data grid.
Apologies my bad..i am a boof head.
Tha datagrid IS bound automatically. Ive just realised i was calling my initial dataset() method - which is calling my database, in my datagrid_load method. thus everytime i was populating the datagrid, it was actually refreshing from the database not the datatable.
Thankyou your repy tho..