Cancel/insert/update not saving to the DB - c#

I am working on Northwind database reproducing this demo. The code is not showing any error but all operations insert/update/delete are only temporary. If I add a record or cancel or update the next time I run the code, the content of the table is still the original one without any of the modification I did saved inthe db.
private static DataTable GetDataTable(string queryString)
{
String connString = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(connString);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = new SqlCommand(queryString, mySqlConnection);
DataTable myDataTable = new DataTable();
mySqlConnection.Open();
try
{
mySqlDataAdapter.Fill(myDataTable);
}
finally
{
mySqlConnection.Close();
}
return myDataTable;
}
private DataTable Employees
{
get
{
object obj = this.Session["Employees"];
if ((!(obj == null)))
{
return ((DataTable)(obj));
}
DataTable myDataTable = new DataTable();
myDataTable = GetDataTable("SELECT * FROM Employees");
this.Session["Employees"] = myDataTable;
return myDataTable;
}
}
protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
this.RadGrid1.DataSource = this.Employees;
this.Employees.PrimaryKey = new DataColumn[] { this.Employees.Columns["EmployeeID"] };
}
protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
//Prepare new row to add it in the DataSource
DataRow[] changedRows = this.Employees.Select("EmployeeID = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["EmployeeID"]);
if (changedRows.Length != 1)
{
RadGrid1.Controls.Add(new LiteralControl("Unable to locate the Employee for updating."));
e.Canceled = true;
return;
}
//Update new values
Hashtable newValues = new Hashtable();
newValues["Country"] = (userControl.FindControl("TextBox7") as TextBox).Text;
newValues["City"] = (userControl.FindControl("TextBox8") as TextBox).Text;
newValues["Region"] = (userControl.FindControl("TextBox9") as TextBox).Text;
newValues["HomePhone"] = (userControl.FindControl("HomePhoneBox") as RadMaskedTextBox).Text;
newValues["BirthDate"] = (userControl.FindControl("BirthDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["TitleOfCourtesy"] = (userControl.FindControl("ddlTOC") as DropDownList).SelectedItem.Value;
newValues["Notes"] = (userControl.FindControl("TextBox1") as TextBox).Text;
newValues["Address"] = (userControl.FindControl("TextBox6") as TextBox).Text;
newValues["FirstName"] = (userControl.FindControl("TextBox2") as TextBox).Text;
newValues["LastName"] = (userControl.FindControl("TextBox3") as TextBox).Text;
newValues["HireDate"] = (userControl.FindControl("HireDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["Title"] = (userControl.FindControl("TextBox4") as TextBox).Text;
changedRows[0].BeginEdit();
try
{
foreach (DictionaryEntry entry in newValues)
{
changedRows[0][(string)entry.Key] = entry.Value;
}
changedRows[0].EndEdit();
this.Employees.AcceptChanges();
}
catch (Exception ex)
{
changedRows[0].CancelEdit();
Label lblError = new Label();
lblError.Text = "Unable to update Employees. Reason: " + ex.Message;
lblError.ForeColor = System.Drawing.Color.Red;
RadGrid1.Controls.Add(lblError);
e.Canceled = true;
}
}
protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
{
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
//Create new row in the DataSource
DataRow newRow = this.Employees.NewRow();
//Insert new values
Hashtable newValues = new Hashtable();
newValues["Country"] = (userControl.FindControl("TextBox7") as TextBox).Text;
newValues["City"] = (userControl.FindControl("TextBox8") as TextBox).Text;
newValues["Region"] = (userControl.FindControl("TextBox9") as TextBox).Text;
newValues["HomePhone"] = (userControl.FindControl("HomePhoneBox") as RadMaskedTextBox).Text;
newValues["BirthDate"] = (userControl.FindControl("BirthDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["TitleOfCourtesy"] = (userControl.FindControl("ddlTOC") as DropDownList).SelectedItem.Value;
newValues["Notes"] = (userControl.FindControl("TextBox1") as TextBox).Text;
newValues["Address"] = (userControl.FindControl("TextBox6") as TextBox).Text;
newValues["FirstName"] = (userControl.FindControl("TextBox2") as TextBox).Text;
newValues["LastName"] = (userControl.FindControl("TextBox3") as TextBox).Text;
newValues["HireDate"] = (userControl.FindControl("HireDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["Title"] = (userControl.FindControl("TextBox4") as TextBox).Text;
//make sure that unique primary key value is generated for the inserted row
newValues["EmployeeID"] = (int)this.Employees.Rows[this.Employees.Rows.Count - 1]["EmployeeID"] + 1;
try
{
foreach (DictionaryEntry entry in newValues)
{
newRow[(string)entry.Key] = entry.Value;
}
this.Employees.Rows.Add(newRow);
this.Employees.AcceptChanges();
}
catch (Exception ex)
{
Label lblError = new Label();
lblError.Text = "Unable to insert Employees. Reason: " + ex.Message;
lblError.ForeColor = System.Drawing.Color.Red;
RadGrid1.Controls.Add(lblError);
e.Canceled = true;
}
}
protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
{
string iD = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["EmployeeID"].ToString();
DataTable employeeTable = this.Employees;
if (employeeTable.Rows.Find(iD) != null)
{
employeeTable.Rows.Find(iD).Delete();
employeeTable.AcceptChanges();
}
}
Why my insert/delete/update are only temporary and visible in the current session? How can I fix this to get insert/update/delete changing the data in the database?

Acknowledge that Rows.Add() or AcceptChanges() do NOT write anything to the underlying database. They only operate on the in-memory data structures such as DataTables and DataSets. To actually save changes, you must:
Either use TableAdapter.Update() method and supply your modified DataTable to it.
Use SqlCommand and manually execute UPDATE, INSERT and DELETE commands.
You must NOT call AcceptChanges() before sending your changes back to the database.

Related

Why do I get the value System.Data.DataRowView? c#

Why do I get the value System.Data.DataRowView? c# + sqlserver
I'm trying to add data to my table but ne system.Data.rowview and I don't know how to do it so that it doesn't come out
Why do I get the value System.Data.DataRowView? c# + sqlserver
This is where I load the items inside the Checklixbox
public void Cargar_Requerimientos(string Id_CR)
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT Id_CR, Requisitos, Id_RS FROM Requerimientos WHERE Id_CR =#Id_CR ", cn);
cmd.Parameters.AddWithValue("Id_CR", Id_CR);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cn.Close();
//DataRow dr = dt.NewRow();
//dr["Requisitos"] = "Seleciona un Requisitos";
// dt.Rows.InsertAt(dr, 0);
///////////////////////////////////////
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";
checkedListBox1.DataSource = dt;
//bool state = true;
// for (int i = 0; i < checkedListBox1.Items.Count; i++)
// checkedListBox1.SetItemCheckState(i, (state ? CheckState.Checked : CheckState.Unchecked));
//dr = dt.NewRow();
enter code here
try
{
//checkedListBox1.DataSource = dt.Columns[0].ToString();
//dt.Columns[0].ToString();
//checkedListBox1.DataSource = dt.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
here I upload the data from combobox1 to checklistbox1
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// checkedListBox1.Enabled = false;
{
if (comboBox1.SelectedItem.ToString() == null)
{
checkedListBox1.Enabled = true;
}
}
if (comboBox1.SelectedValue.ToString() != null)
{
string Id_CR = comboBox1.SelectedValue.ToString();
Cargar_Requerimientos(Id_CR);
}
Result:
The CheckListBox does not directly support a DataSource, which is why the property is hidden from intellisence.
Usually it is correct to set the DataSource after setting the DisplayMember and ValueMember properties, to avoid multiple refresh calls, but to avoid your issue, you have to set the DataSource property first:
checkedListBox1.DataSource = dt;
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";

keydown Event can't add item in datagridview

When I use the scanner to scan the barcode,
the item will be add in the first row and when I scan the second barcode,
the item will no add in the datagridview but it just adds a row only.
My column in datagridview is productid, ProductName, Description, Stock, UOM, Price
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DataGridViewRow newRow = new DataGridViewRow();
if (textBox1.Text.Length != 0)
{
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.RowCount -1;
dataGridView1.Rows.Insert(i);
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[i].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[i].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = item[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = item[5].ToString();
}
}
}
}
Page Screenshots:
https://ibb.co/pJ0fnx7
Your approach if your productid is a unique key as it should be, will always be returning only one result, I really dont see the need of the foreach statement here. Moreover every time you open a conn to the database you should be closing it.
My approach with this in mind would be a little different this would be
Public Class clsConn
{
Public List<Data> getSomething()
var SqlConn = new SqlConnection("your connection");
try
{
SqlConn.Open();
string sqlstring = "your sql sentence";
SqlCommand SqlCmd = new SqlCommand(sqlstring, SqlConn);
SqlDataReader reader = SqlCmd.ExecuteReader();
List<Data> dataList = new List<Data>();
if (reader.Read())
{
Data data = new Data();
data.productid = reader[0].ToString(); // this is just an example
dataList.Add(data);
}
return dataList;
}
catch (Exception ex)
{
MessageBox.Show("conexion to DB failed: " + ex.Message);
throw;
}
finally
{
SqlConn.Close();
}
}
}
}
And you should have a public data class that has all the properties you need like this for example
public class Data
{
public string productid { get; set; }
}
To use it, you have to work like this
List<Data> dbData = new List<Data>();
clsConn db = new clsConn();
dbData = db.getSomething();
//I ll leave the foreach but as I said this should be only one result
foreach (var item in DBData)
{
dataGridView1.Rows.Add(item.productid);
}
Your .Insert()-call does not provide the row to insert, and you do not handle the index returned from the Rows.Add()-call.
I have edited your code a bit so that it should work now.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode != Keys.Enter) || (textBox1.Text.Length == 0))
{
return;
}
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.Rows.Add();
DataGridViewRow row = dataGridView1.Rows[i];
row.Cells[0].Value = item[0].ToString();
row.Cells[1].Value = item[1].ToString();
row.Cells[2].Value = item[2].ToString();
row.Cells[3].Value = item[3].ToString();
row.Cells[4].Value = item[4].ToString();
row.Cells[5].Value = item[5].ToString();
}
}
And do not forget to close your database connection. Consider using the using-statement for this.
You should also check this: How to add a new row to datagridview programmatically

How to save changes to DataView to Database on button click?

I'm new to Asp.net and I'm trying to figure out how to update a value in a SqlDataSource programmatically. Here's my button click listener:
protected void ApproveLoanButton_Click(object sender, EventArgs e)
{
DataView dv = (DataView)DetailsSqlDataSource.Select(DataSourceSelectArguments.Empty);
dv.AllowEdit = true;
using (var dt = dv.ToTable())
{
var oldValue = dt.Rows[0]["IsApproved"].ToString();
dt.Rows[0]["IsApproved"] = true;
var newValue = dt.Rows[0]["IsApproved"].ToString();
dt.AcceptChanges();
GridView1.DataBind();
DetailsView1.DataBind();
}
}
The oldValue is false and the newValue is true so I am changing the value but it doesn't save to the database when I call AcceptChanges(). What am I doing wrong here? I've already spent hours on this. Thanks for your help!
I do not have what your DetailsSqlDataSource is, or what your database structure is like, but you would obviously need to write a few Save and Read methods.
If you did that, you would have something like this:
protected void ApproveLoanButton_Click(object sender, EventArgs e)
{
DataView dv = (DataView)DetailsSqlDataSource.Select(DataSourceSelectArguments.Empty);
dv.AllowEdit = true;
using (var dt = dv.ToTable())
{
var oldValue = dt.Rows[0]["IsApproved"].ToString();
if (-1 < SaveApproved((int)dt.Rows[0]["ID"], true))
{
dt.Rows[0]["IsApproved"] = true;
var newValue = dt.Rows[0]["IsApproved"].ToString();
dt.AcceptChanges();
DetailsSqlDataSource = GetTable();
GridView1.DataBind();
DetailsView1.DataBind();
}
}
}
You will need to modify these to work, but here is a sample:
private const string SQL_CONNECTION = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
private DataTable GetTable()
{
var table = new DataTable();
using (var con = new System.Data.SqlClient.SqlConnection(SQL_CONNECTION))
{
con.Open();
using (var cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM MyTable;", con))
{
table.Load(cmd.ExecuteReader());
}
}
return table;
}
private int SaveApproved(int rowID, bool approved)
{
using (var con = new System.Data.SqlClient.SqlConnection(SQL_CONNECTION))
{
con.Open();
using (var cmd = new System.Data.SqlClient.SqlCommand("UPDATE MyTable SET IsApproved=#IsApproved WHERE ID=#ID;", con))
{
cmd.Parameters.Add("#IsApproved", SqlDbType.Bit).Value = approved;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = rowID;
return cmd.ExecuteNonQuery();
}
}
}

Delete the single selected row from a grid view at run time

I have a table having 2 columns viz ID and DETAILS.Data in a table is like
id=01 details="pritam=123 sourav=263" like this
i am working on a windows for application ..when the application will run the output comes what i am going to tell.. 1.in my application one combobox is there.when the application will run all the id will be bind in a combobox from the table. 2.when user will choose any id suddenly the details column data will be shown in a datagrid view in a splitted format like this.
NAME KEY
PRITAM 123
SOURAV 263
in this data grid view user can delete ant row by selecting the and click on the below delete button. insert any row by clickng the add new row button at the end ,modify any existing data and finally click on the update button and all the data are going to be stored in that data base like in previous format.. for that i have written the code in c# like this..
namespace windows_csharpp
{
public partial class Form5 : Form
{
SqlConnection cc = new SqlConnection("Integrated Security=true;database=EDIXfer");
SqlDataAdapter da;
DataTable dt;
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
string sql="select EDIScheduleID from ETAProcessSchedule";
da= new SqlDataAdapter(sql, cc);
dt = new System.Data.DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
comboBox1.Items.Add(dt.Rows[x][0].ToString());
}
}
ArrayList ls = new ArrayList();
int ss = 0;
int ss1 = 0;
int ssp = 1;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "select * from ETAProcessSchedule where EDIScheduleID='" + comboBox1.SelectedItem.ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(sql, cc);
DataTable dt = new System.Data.DataTable();
adp.Fill(dt);
string stp = dt.Rows[0][21].ToString();
string[] stp1 = stp.Split(' ');
List<Class1> lst = new List<Class1>();
ls.Clear();
for (int x = 0; x < stp1.Length; x++)
{
ls.Add(stp1[x].ToString());
}
for (int x = 0; x < ls.Count; x++)
{
string ssttt = ls[x].ToString();
string[] sssp = ssttt.Split('=');
for (int x1 = 1; x1 < sssp.Length; x1++)
{
ss = 0;
ss1 = ssp;
Class1 cs = new Class1()
{
Value = sssp[ss], Key= sssp[x1].ToString()
};
lst.Add(cs);
}
}
dataGridView1.DataSource = lst;
}
private void Update_Click(object sender, EventArgs e)
{
string value = null;
string keys = null;
string query = null;
string str = null;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
value = dataGridView1.Rows[i].Cells[0].Value.ToString();
keys = dataGridView1.Rows[i].Cells[1].Value.ToString();
string ss = value + '=' + keys;
str += ss + ' ';
}
query = "update ETAProcessSchedule set ProcParameters='"+str+"' where EDIScheduleID='"+comboBox1.SelectedItem.ToString()+"'";
da = new SqlDataAdapter(query, cc);
dt = new DataTable();
da.Fill(dt);
MessageBox.Show("Data Updated In Database Successfully");
}
and one class file is also there ..
class Class1
{
public string Value { get; set; }
public string Key { get; set; }
}
kindly help me in delete the selected row ,add the new row and update the all data in database like in previous format..
I think you already have working approach. If I understand right you need only two functions:
- Load Schedule details in the DataGridView (one key-value pair per row)
- Save edited/added/deleted key-value pairs to the database
Be sure next properties of DataGridView set to true:
this.YourDataGridView.AllowUserToAddRows = true;
this.YourDataGridView.AllowUserToDeleteRows = true;
And of course columns must be editable
In the methods was used const variables which was created in your Form (Form1)
private const string DETAILSDELIMITER = ' ';
private const string NAMEKEYDELIMITER = '=';
Method for loading schedule details in the DataGridView
//Use SqlParameters in the query,
//if not your application vulnerable for sql injection
private void LoadScheduleDetails(string scheduleID)
{
//You working only with one column, do not use '*' in SELECT statement if not nessesary
string query = "SELECT EDIScheduleID, ProcParameters FROM ETAProcessSchedule WHERE EDIScheduleID = #ScheduleID";
DataTable details = new DataTable();
//Get data from database
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using(SqlCommand detailsCommand = new SqlCommand(query, yourConnection))
{
//Adding parameter
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
detailsCommand.Parameters.Add(id);
using (SqlDataAdapter yourAdapter = new SqlDataAdapter(detailsCommand ))
{
yourAdapter.Fill(details);
}
}
}
this.YourDataGridView.Rows.Clear();
if (details.Rows.Count > 0)
{
DataRow temp = details.Rows[0];
//get column by name.
string[] pairs = temp.Field<String>("ProcParameters").Split(Form1.DETAILSDELIMITER);
//Adding rows manually without DataSource
foreach(string pair in pairs)
{
this.YourDataGridView.Rows.Add(pair.Split(Form1.NAMEKEYDELIMITER));
}
}
}
Method for saving data
I think better if you create columns already in the designer
Then you can access columns by it's name without hardcoding indexes
private void SaveDetails(string scheduleID)
{
StringBuilder details = new StringBuilder();
foreach(DataGridViewRow dgvr in this.YourDataGridView.Rows)
{
string name = dgvr.Cells[this.dgvColumn_Name.Name].Value.ToString();
string key = dgvr.Cells[this.dgvColumn_Key.Name].Value.ToString();
//Here you can check if values are ok(not empty or something else)
//Create pair
details.Append(Form1.DETAILSDELIMITER);
details.Append(name);
details.Append(Form1.NAMEKEYDELIMITER);
details.Append(key);
}
//remove first space character
if (details.Length > 0)
details.Remove(0, 1);
//Save data to database
string query = "UPDATE ETAProcessSchedule SET ProcParameters=#Details WHERE EDIScheduleID=#ScheduleID";
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using (SqlCommand saveCommand = new SqlCommand(query, yourConnection))
{
//Adding parameters
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
SqlParameter procParams = new SqlParameter { ParameterName = "#Details", SqlDbType = SqlDbType.NVarChar, Value = details.ToString() };
saveCommand.Parameters.Add(id);
saveCommand.Parameters.Add(procParams);
saveCommand.ExecuteNonQuery();
MessageBox.Show("Data Updated In Database Successfully");
}
}
}
Then use LoadScheduleDetails in the comboBox1_SelectedIndexChanged eventhandler
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.LoadScheduleDetails(scheduleID);
}
}
After data loaded, user can change it, add rows, delete rows
When user pressed "Update" button then use SaveDetails method,
where we collect data from all rows and update database with it
private void Update_Click(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.SaveDetails(scheduleID);
}
}
On your form load bind data:-
EDIT : -
private void Form5_Load(object sender, EventArgs e)
{
comboBox1.DataSource = loadddltable();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
}
public DataTable loadddl()
{
OleDbDataReader obj = null;
DataTable dt = new DataTable();
try
{
obj_dbconnection.CommandText = "Select * from TableName";
obj = obj_dbconnection.ExecuteReader();
if (obj != null)
{
if (obj.HasRows)
{
dt.Load(obj);
}
}
}
catch (Exception)
{
}
finally
{
if (obj != null)
{
obj.Close();
obj_dbconnection.Close();
}
}
return dt;
}
/*Code for Execute Reader*/
public OleDbDataReader ExecuteReader()
{
OleDbDataReader dr = null;
try
{
Open();
dr = cmd.ExecuteReader();
}
catch(Exception)
{ }
return dr;
}
/*Code for binding grid data*/
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource= getDataForSelectedId(comboBox1.SelectedValue);
}
And then insert,edit,delete buttons as template fields to dataGridView and use dataGridView1_CellClick event to insert edit delete

Can not get last selected item in DataGridViewComboBoxCell

my problem is like that: I have a C# application having datagridview which has some textboxes and comboboxes in its columns. All the columns get the data from a database. Textboxes are readonly. When i ask for values in each row, i get the last selected component's value (i.e. combobox' value because textboxes are readonly) as null.
For example:
I have 10 cells in a row. The comboboxes are at 7th, 8th and 9th indexes in a row, where indexes from 0 to 6 are texboxes. When i select 3 of them (in order of 7, 8, 9) i cannot get the cell value of 9.
row.Cells[7].Value is OK,
row.Cells[8].Value is OK, and
row.Cells[9].Value is null
When i select any two of them let say first 8 and then 7, i cannot get the cell value of 7.
row.Cells[8].Value is OK and
row.Cells[7].Value is null
When i select only one item let say 9, i got the cell value again null.
As a result i get the last selected DataGridViewComboBoxCell as null.
Can anyone help me in my problem please? Thanks for all your help.
Here is my code:
private void cmbVariable_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = sender as ComboBox;
BringQuery(cmb.SelectedItem.ToString());
}
private void BringQuery(string option)
{
SqlConnection conn = new SqlConnection("Server = 10.2.6.14; Database = TTS; uid = myuser; password = mypassword");
DataTable dt1 = new DataTable();
SqlCommand cmd1 = new SqlCommand("select Track_Number, Parking_Area, Mission_Number, Track_Info, Time, Direction, Explanation from Traffic_Run_Table where Op_Type=#myType", conn);
SqlCommand cmd2 = new SqlCommand("select * from Traffic_Track_Table", conn);
SqlCommand cmd3 = new SqlCommand("select * from Traffic_Driver order by Id_Number", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
cmd1.Parameters.Add(new SqlParameter("myType", option));
try
{
conn.Open();
sda1.Fill(dt1);
dataGridView2.AutoGenerateColumns = false;
foreach (DataGridViewColumn col in dataGridView2.Columns)
{
col.DataPropertyName = col.Name;
}
dataGridView2.DataSource = dt1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
DataGridViewComboBoxColumn cmbCol1, cmbCol2, cmbCol3;
SqlDataAdapter sda2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
try
{
cmbCol1 = new DataGridViewComboBoxColumn();
cmbCol1.HeaderText = "Track 1";
cmbCol1.Name = "Track1";
cmbCol1.DataPropertyName = cmbCol1.Name;
cmbCol1.ValueType = typeof(int);
cmbCol1.Width = 50;
cmbCol2 = new DataGridViewComboBoxColumn();
cmbCol2.HeaderText = "Track 2";
cmbCol2.Name = "Track2";
cmbCol2.DataPropertyName = cmbCol2.Name;
cmbCol2.ValueType = typeof(int);
cmbCol2.Width = 50;
sda2.Fill(dt2);
dt2.Columns[0].ColumnName = "Track";
foreach (DataRow dr in dt2.Rows)
{
cmbCol1.Items.Add(Convert.ToInt32(dr["Track"]));
cmbCol2.Items.Add(Convert.ToInt32(dr["Track"]));
}
dataGridView2.Columns.Add(cmbCol1);
dataGridView2.Columns.Add(cmbCol2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlDataAdapter sda3 = new SqlDataAdapter(cmd3);
DataTable dt3 = new DataTable();
try
{
cmbCol3 = new DataGridViewComboBoxColumn();
cmbCol3.HeaderText = "Driver";
cmbCol3.Name = "Driver";
cmbCol3.DataPropertyName = cmbCol3.Name;
cmbCol3.ValueType = typeof(string);
cmbCol3.Width = 260;
sda3.Fill(dt3);
dt3.Columns[0].ColumnName = "Id";
dt3.Columns[1].ColumnName = "Driver";
dt3.Columns[2].ColumnName = "Mission";
foreach (DataRow dr in dt3.Rows)
{
cmbCol3.Items.Add(Convert.ToString(dr["Id"]).Trim() + " - " + Convert.ToString(dr["Dirver"]).Trim() + " - " + Convert.ToString(dr["Mission"]).Trim());
}
dataGridView2.Columns.Add(cmbCol3);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
public string CheckNull(object value, Type objType)
{
string retVal = string.Empty;
if (value == null || value.ToString() == " " || value.ToString() == "")
{
if (objType == typeof(int))
{
retVal = "0";
}
if (objType == typeof(string))
{
retVal = "-";
}
}
else
{
retVal = value.ToString();
}
return retVal;
}
private void Save_Click(object sender, EventArgs e)
{
SqlConnection connForSave = new SqlConnection("Server = 10.2.6.14; Database = TTS; uid = myuser; password = mypassword");
SqlCommand cmdForSave = new SqlCommand("insert into Traffic_Records values (#type, #trackNumber, #parkingArea, #missionNmb, #trackInfo, #time, #direction, #explanation, #track1, #track2, #driverId, #driverName, #driverMission, #date)", connForSave);
foreach (DataGridViewRow row in dataGridView2.Rows)
{
try
{
dataGridView2[7, row.Index].Selected = false;
dataGridView2[8, row.Index].Selected = false;
dataGridView2[9, row.Index].Selected = false;
connForSave.Open();
cmdForSave.Parameters.AddWithValue("type", CheckNull(cmbVairable.SelectedItem.ToString(), typeof(string)));
cmdForSave.Parameters.AddWithValue("trackNumber", Convert.ToInt16(CheckNull(row.Cells[0].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("parkingArea", CheckNull(row.Cells[1].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("missionNmb", Convert.ToInt16(CheckNull(row.Cells[2].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("trackInfo", CheckNull(row.Cells[3].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("time", CheckNull(row.Cells[4].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("direction", CheckNull(row.Cells[5].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("explanation", CheckNull(row.Cells[6].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("track1", Convert.ToInt16(CheckNull(row.Cells[7].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("track2", Convert.ToInt16(CheckNull(row.Cells[8].Value, typeof(int))));
string[] sArray = null;
if (string.Compare(CheckNull(row.Cells[9].Value, typeof(string)), "0") != 0 && string.Compare(CheckNull(row.Cells[9].Value, typeof(string)), "-") != 0)
{
sArray = row.Cells[9].Value.ToString().Split('-');
sArray[0] = sArray[0].Remove(sArray[0].Length - 2, 1);
sArray[1] = sArray[1].Remove(0, 1);
sArray[1] = sArray[1].Remove(sArray[1].Length - 2, 1);
sArray[2] = sArray[2].Remove(0, 1);
}
else
{
string temp = "0 - -";
sArray = temp.Split(' ');
}
cmdForSave.Parameters.AddWithValue("driverId", Convert.ToInt16(sArray[0]));
cmdForSave.Parameters.AddWithValue("driverName", sArray[1]);
cmdForSave.Parameters.AddWithValue("driverMission", sArray[2]);
cmdForSave.Parameters.AddWithValue("date", DateTime.Now);
cmdForSave.ExecuteNonQuery();
cmdForSave.Parameters.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n Line Number: " + ex.LineNumber());
}
connForSave.Close();
}
}
This happens because DataGridView does not commit user made changes instantly but only after row is validated (I think, may be wrong here). So after you selected last value and did not change row (so validate event has not fired) the value in combo box is still null.
To fix this add CurrentCellDirtyStateChanged (more info here MSDN event to your grid:
private void GridCurrentCellDirtyStateChanged(object sender, EventArgs e)
{
dgvAssignedProperties.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
and this why new values are committed right away.

Categories