I am new to C#. I want to create combobox in first column of my Datagridview. Following is the routine I have wrote. But it is adding combo in last column after setting up my grid.
For setting up Grid, i have tried the below code:
private void SetGrid()
{
dgDetail.AutoGenerateColumns = false;
dgDetail.ColumnCount = 5;
dgDetail.Columns[0].Name = "Debit";
dgDetail.Columns[0].HeaderText = "Debit Account Name";
dgDetail.Columns[1].Name = "Bank";
dgDetail.Columns[1].HeaderText = "Bank";
dgDetail.Columns[2].Name = "ChqNo";
dgDetail.Columns[2].HeaderText = "CC/Chq No";
dgDetail.Columns[3].Name = "ChqDate";
dgDetail.Columns[3].HeaderText = "Chq Date";
dgDetail.Columns[4].Name = "Amount";
dgDetail.Columns[4].HeaderText = "Amount";
dgDetail.AllowUserToDeleteRows = true;
dgDetail.Columns[0].Width = 280;
dgDetail.Columns[1].Width = 160;
dgDetail.Columns[2].Width = 90;
dgDetail.Columns[3].Width = 90;
dgDetail.Columns[4].Width = 120;
dgDetail.RowsDefaultCellStyle.ForeColor = Color.Black;
dgDetail.RowsDefaultCellStyle.BackColor = Color.White;
dgDetail.Font = new Font("Arial", 9, FontStyle.Regular);
}
For Creating the combobox which is filled from DB.
private void FillGridCombo()
{
SqlConnection sqlConnection = new SqlConnection(strCon);
sqlConnection.Open();
try
{
string selectQueryStringMonth = "SELECT accode, GLAC FROM glmast where (actype = 'CSH' and titleac <> 'PDP') OR TITLEAC = 'DIS' ORDER BY GLAC";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectQueryStringMonth, sqlConnection);
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
BindingSource bindingSourceMonth = new BindingSource();
bindingSource.DataSource = dataTable;
//Adding Combo
DataGridViewComboBoxColumn ColumnAcc = new DataGridViewComboBoxColumn();
ColumnAcc.DataPropertyName = "Debit Account Name";
ColumnAcc.HeaderText = "Debit Account Name";
ColumnAcc.Width = 280;
ColumnAcc.DataSource = bindingSourceMonth;
ColumnAcc.ValueMember = "accode";
ColumnAcc.DisplayMember = "GLAC";
dgDetail.Columns.Add(ColumnAcc);
dgDetail.DataSource = bindingSource;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (sqlConnection.State != ConnectionState.Closed)
sqlConnection.Close();
}
}
I am calling both procedures on my NewData() like this.
private void NewData()
{
if (dgDetail.DataSource != null)
dgDetail.DataSource = null;
else
dgDetail.Rows.Clear();
ClearData();
CtrlEnable();
SetGrid();
FillGridCombo();
}
Help / Guide me to achieve this.,
use
dgDetail.Columns.Insert(0, ColumnAcc);
instead of
dgDetail.Columns.Add(ColumnAcc);
when you use Add it simply adds it as the last column, while using Insert you can choose where to add it to.
public virtual void Insert( int columnIndex, DataGridViewColumn
dataGridViewColumn )
note that the columnIndex is a zero-based index so 0 is the first column
You can use the Insert method instead of Add like this:
dgDetail.Columns.Insert(0,ColumnAcc);
Related
Currently my system is connected via mysql data base to get the data from mysql to dgv.
I need a code that can blend with my current code on sorting the data when clicked on header. Sorry for poor english.
private void btnDisplay_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString; //Set your MySQL connection string here.
string query = "SELECT lrn,first_name,middle_name,last_name,grade_and_section,student_gender,student_guardian,contact_number FROM student_info;"; // set query to fetch data "Select * from tabelname";
using (MySqlConnection conn = new MySqlConnection(connString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dataStudent.DataSource = ds.Tables[0];
dataStudent.Columns[0].HeaderCell.Value = "LRN";
dataStudent.Columns[1].HeaderCell.Value = "First Name";
dataStudent.Columns[2].HeaderCell.Value = "Middle Name";
dataStudent.Columns[3].HeaderCell.Value = "Last Name";
dataStudent.Columns[4].HeaderCell.Value = "Grade And Section";
dataStudent.Columns[5].HeaderCell.Value = "Gender";
dataStudent.Columns[6].HeaderCell.Value = "Guardian";
dataStudent.Columns[7].HeaderCell.Value = "Contact Number";
dataStudent.Columns[5].Visible = false;
dataStudent.Columns[6].Visible = false;
dataStudent.Columns[7].Visible = false;
}
}
}
private void dataStudent_CellClick(object sender, DataGridViewCellEventArgs e)
{
int index = e.RowIndex;
DataGridViewRow selectedRow = dataStudent.Rows[index];
txtLRN.Text = selectedRow.Cells[0].Value.ToString();
txtFName.Text = selectedRow.Cells[1].Value.ToString();
txtMName.Text = selectedRow.Cells[2].Value.ToString();
txtLName.Text = selectedRow.Cells[3].Value.ToString();
txtYear.Text = selectedRow.Cells[4].Value.ToString();
txtGender.Text = selectedRow.Cells[5].Value.ToString();
txtGuardian.Text = selectedRow.Cells[6].Value.ToString();
txtContact.Text = selectedRow.Cells[7].Value.ToString();
}
this is the property | this is the pic
i cant seem to resize my column width in Datagridview. Here is my code:
public void dgvwidth()
{
crud.FillDataGrid("Select ProductID,BrandName,Dosage from ProductItems", ref dgvOrderproductlist);
dgvOrderproductlist.Columns[0].Width = 80;
dgvOrderproductlist.Columns[1].Width = 250;
dgvOrderproductlist.Columns[2].Width = 80;
}
private void HomePage_Load(object sender, EventArgs e)
{
dgvwidth();
}
I'm trying to get just 3 columns from my table and change it column width to fit my Datagridview. its not getting any error but its not changing the column width as well.
public void FillDataGrid(string sql, ref DataGridView dg)
{
try
{
DataSet ds = new DataSet();
cn.Open();
cmd = new SqlCommand(sql, cn);
adptr = new SqlDataAdapter(cmd);
adptr.Fill(ds);
dg.DataSource = "";
dg.DataSource = ds.Tables[0];
dg.AutoResizeColumns();
}
catch (Exception e)
{
MessageBox.Show("" + e.Message);
}
cn.Close();
}
Can you try like this
public void dgvwidth()
{
crud.FillDataGrid("Select ProductID,BrandName,Dosage from ProductItems", ref dgvOrderproductlist);
var column = dgvOrderproductlist.Columns[0];
column.Width = 80;
column = dgvOrderproductlist.Columns[1];
column.Width = 250;
column = dgvOrderproductlist.Columns[2];
column.Width = dgvOrderproductlist.Width - dgvOrderproductlist.Columns[0].Width - dgvOrderproductlist.Columns[1].Width - 50;
}
Let say I have 2 datagridview fullrowselect and each of them has two columns.for example like this one
DGV1 DGV2
ControlNum|Title ControlNum|Title
0132 |avengers 0112 |X-men
0112 |X-men 0231 |Transformers
0234 |spiderman 0123 |Thor
now I want to compare Dvg2's list to DGV1 if DGV2 contains the same data in dgv1 then i want to color the background cell of that row in dgv2 into red if not remain as is..
code for loading db
void loadDB()//dgv1
{
string query = "SELECT animelist.ControlNum,TitleAnime FROM maindatabase.watchlist inner join maindatabase.animelist on watchlist.ControlNum = animelist.ControlNum where idnum=?para;";
using (MySqlConnection conn = new MySqlConnection(myConnection))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("?para",int.Parse(MyList.AccountControlNum.ToString()));
try
{
this.Controls.Add(grid);
sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
datset = new DataTable();
grid.DataSource = datset;
sda.Fill(datset);
bsource = new BindingSource();
grid.BackgroundImage = Properties.Resources.Kurumi;
grid.SetCellsTransparent();
grid.Width = 271;
grid.Height = 391;
grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
grid.AllowUserToDeleteRows = false;
grid.AllowUserToAddRows = false;
grid.AllowUserToResizeColumns = false;
grid.AllowUserToResizeRows = false;
grid.ReadOnly = true;
grid.AllowDrop = false;
grid.MultiSelect = false;
grid.ColumnHeadersVisible = true;
grid.RowHeadersVisible = false;
grid.ScrollBars = ScrollBars.Vertical;
grid.Sort(grid.Columns[1], ListSortDirection.Ascending);
DataGridViewColumn column = grid.Columns[0];
column.Visible = false;
try
{
grid.CurrentCell = grid[1, 0];
}
catch { }
my = this.Parent.Parent as MyList;
my.label5.Text = grid.RowCount.ToString();
DataGridViewColumn column1 = grid.Columns[1];
column1.HeaderText = "WatchList";
// column1.DefaultCellStyle.Alignment = MiddleCenter;
column1.Width = 265;
sda.Update(datset);
grid.SelectionChanged += grid_SelectionChanged;
grid.CellMouseDown += grid_CellMouseDown;
if (grid.RowCount < 1)
{
my.OpenDetailsWL.Enabled = false;
//openToolStripMenuItem.Enabled = false;
}
else if (grid.RowCount > 0)
{
my.OpenDetailsWL.Enabled = true;
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
conn.Close();
}
}
dgv 2
void loadDB()
{
SuspendLayout();
string query = "SELECT ControlNum,TitleAnime FROM maindatabase.animelist";
using (MySqlConnection conn = new MySqlConnection(myConnection))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
try
{
panel5.Controls.Add(grid);
sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
datset = new DataTable();
grid.DataSource = datset;
sda.Fill(datset);
bsource = new BindingSource();
grid.BackgroundImage = Properties.Resources.My;
grid.SetCellsTransparent();
grid.Width = 271;
grid.Height = 391;
grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
grid.AllowUserToDeleteRows = false;
grid.AllowUserToAddRows = false;
grid.AllowUserToResizeColumns = false;
grid.AllowUserToResizeRows = false;
grid.ReadOnly = true;
grid.AllowDrop = false;
grid.MultiSelect = false;
grid.ColumnHeadersVisible = false;
grid.RowHeadersVisible = false;
grid.ScrollBars = ScrollBars.Vertical;
grid.Sort(grid.Columns[1], ListSortDirection.Ascending);
//bsource.DataSource = datset;
//dataGridView1.DataSource = bsource;
DataGridViewColumn column = grid.Columns[0];
column.Visible = false;
try
{
grid.CurrentCell = grid[1, 0];
}
catch { }
label2.Text= grid.RowCount.ToString();
DataGridViewColumn column1 = grid.Columns[1];
column1.Width = 265;
column1.SortMode = DataGridViewColumnSortMode.Programmatic;
sda.Update(datset);
grid.SelectionChanged += grid_SelectionChanged;
grid.CellMouseDown += grid_CellMouseDown;
if (grid.RowCount < 1)
{
openToolStripMenuItem.Enabled = false;
}
else if (grid.RowCount > 0)
{
openToolStripMenuItem.Enabled = true;
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
conn.Close();
}
ResumeLayout();
Your List 1 contains your watchlist table; your List 2 contains your animelist table.
If you retrieve both lists from the same database and want to highlight records being in both source tables in your animelist list you can solve this simply by outer join your watchlist table:
dgv2 query:
SELECT
animelist.ControlNum AS 'ControlNum',
animelist.TitleAnime AS 'Title',
IFNULL(watchlist.ControlNum, 0) AS 'WatchNum'
FROM maindatabase.animelist
LEFT JOIN maindatabase.watchlist ON watchlist.ControlNum = animelist.ControlNum
next you'll have to register an event handler on your grid to control the cell formatting:
grid.CellFormatting += grid_CellFormatting;
the event handler will look something like this:
void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (grid.Columns[e.ColumnIndex].Name == "ControlNum")
{
if (e.Value != null)
{
int controlnum;
if (!int.TryParse((String)e.Value, out controlnum) || (controlnum < 1))
{
e.CellStyle.BackColor = Color.Red;
}
}
}
}
A full example can be found on MSDN.
I'm no mysql pro so the query surly can be improved.
In my below code give me this error
error is my gridview textbox column value not inserting in
my database parameter missing error
try {
da=DateTime.Now;
foreach(DataGridViewRow row in dataGridView1.Rows) {
string SelectedText=Convert.ToString((row.Cells["article_name"] as DataGridViewComboBoxCell).FormattedValue.ToString());
string SelectedText1=Convert.ToString((row.Cells["size_name"] as DataGridViewComboBoxCell).FormattedValue.ToString());
string SelectedText2=Convert.ToString((row.Cells["color_name"] as DataGridViewComboBoxCell).FormattedValue.ToString());
string SelectedText3=Convert.ToString((row.Cells["unit_name"] as DataGridViewComboBoxCell).FormattedValue.ToString());
SqlCommand comm=new SqlCommand("abc", con);
con.Open();
comm.Parameters.Add("#order_no", SqlDbType.NVarChar).Value="abc123";
comm.Parameters.Add("#article_name", SqlDbType.NVarChar).Value=SelectedText;
//dataGridView1.Rows[i].Cells["article_name"].Value;
comm.Parameters.Add("#size_name", SqlDbType.NVarChar).Value=SelectedText1;
comm.Parameters.Add("#color_name", SqlDbType.NVarChar).Value=SelectedText2;
comm.Parameters.Add("#quantity", SqlDbType.Int).Value=row.Cells["quantity"].Value;
comm.Parameters.Add("#piece_carton", SqlDbType.Int).Value=row.Cells["pcs_carton"].Value;
comm.Parameters.Add("#no_of_carton", SqlDbType.Int).Value=row.Cells["no_carton"].Value;
comm.Parameters.Add("#unit_name", SqlDbType.NVarChar).Value=SelectedText3;
comm.Parameters.Add("#rate", SqlDbType.NVarChar).Value=row.Cells["rate"].Value;
comm.Parameters.Add("#ship_qty", SqlDbType.Int).Value=row.Cells["ship_qty"].Value;
comm.Parameters.Add("#date1", SqlDbType.DateTime).Value=da;
comm.Parameters.Add("#amount", SqlDbType.NVarChar).Value=row.Cells["amount"].Value;
//comm.CommandText = StrQuery;
db.insertprocedure(comm);
}
}
catch(SqlException ex) {
MessageBox.Show(ex.Message);
}
finally {
con.Close();
}
Here Is My Query
create proc abc
#order_no varchar(50),
#article_name varchar(500),
#size_name varchar(100),
#color_name varchar(100),
#quantity int,
#piece_carton int,
#no_of_carton int,
#unit_name varchar(50),
#rate varchar(50),
#ship_qty int,
#date1 date,
#amount varchar(50)
as
begin
set #date1=CONVERT(varchar,#date1,1)
insert into transaction_order(order_id,article_id,size_id,color_id,quantity,piece_carton,no_of_carton,unit_id,rate,ship_qty,date1,amount)
values(#order_no,(select article_id from article_order where article_name=#article_name),(select size_id from size where size_name=#size_name),(select color_id from color where color_name=#color_name),#quantity,#piece_carton,#no_of_carton,(select unit_id from unit where unit_name=#unit_name),#rate,#ship_qty,#date1,#amount)
end
Here Is MY Function insertprocedure this function is in database class
public void insertprocedure(SqlCommand txt)
{
DateTime da = new DateTime();
try
{
da = DateTime.Now;
con.Open();
txt.CommandType = CommandType.StoredProcedure;
txt.ExecuteNonQuery();
con.Close();
}
catch (Exception ex) { throw ex; }
finally { con.Close(); }
}
> Here Is My Gridview TextBox Columns Added Code
private void Form1_Load(object sender, EventArgs e)
{
string query = "SELECT article_name FROM article_order";
DataTable dt = db.select_command(query);
BindingSource bi = new BindingSource();
bi.DataSource = dt;
string query1 = "SELECT size_name FROM size";
DataTable dt1 = db.select_command(query1);
BindingSource bi1 = new BindingSource();
bi1.DataSource = dt1;
string query2 = "SELECT color_name FROM color";
DataTable dt2 = db.select_command(query2);
BindingSource bi2 = new BindingSource();
bi2.DataSource = dt2;
string query3 = "SELECT unit_name FROM unit";
DataTable dt3 = db.select_command(query3);
BindingSource bi3 = new BindingSource();
bi3.DataSource = dt3;
//string query4 = "SELECT order_no FROM master_order";
//DataTable dt4 = db.select_command(query4);
//BindingSource bi4 = new BindingSource();
//bi4.DataSource = dt4;
#region Gridview Columns
//Transaction Id
DataGridViewTextBoxColumn trans_id = new DataGridViewTextBoxColumn();
trans_id.HeaderText = "ID";
trans_id.Width = 50;
trans_id.DataPropertyName = "ID";
trans_id.Name = "trans_id";
dataGridView1.Columns.Add(trans_id);
//Order No.
//DataGridViewTextBoxColumn order_no = new DataGridViewTextBoxColumn();
//order_no.HeaderText = "Order No";
//order_no.Width = 100;
////order_no.DataPropertyName = "yarn_name";
//order_no.Name = "order_no";
//dataGridView1.Columns.Add(order_no);
//query = "select yarn_name from yarn";
//auto.autocomplete1(dataGridView1., textBox9.AutoCompleteCustomSource = namesCollection, query);
//DataGridViewTextBoxColumn order_no = new DataGridViewTextBoxColumn();
//order_no.HeaderText = "Order No.";
//order_no.Width = 50;
//order_no.DataPropertyName = "order_no";
//order_no.Name = "order_no";
//dataGridView1.Columns.Add(order_no);
//Article Name
DataGridViewComboBoxColumn article_name = new DataGridViewComboBoxColumn();
article_name.DataPropertyName = "Article Name";
article_name.HeaderText = "Article Name";
article_name.Name = "article_name";
article_name.Width = 120;
article_name.DataSource = bi;
article_name.ValueMember = "article_name";
//article_name.DisplayMember = "article_name";
dataGridView1.Columns.Add(article_name);
//Size Name
DataGridViewComboBoxColumn size_name = new DataGridViewComboBoxColumn();
size_name.DataPropertyName = "Size Name";
size_name.HeaderText = "Size Name";
size_name.Name = "size_name";
size_name.Width = 120;
size_name.DataSource = bi1;
size_name.ValueMember = "size_name";
////size_name1.DisplayMember = "size_name";
dataGridView1.Columns.Add(size_name);
//Color Name
DataGridViewComboBoxColumn color_name = new DataGridViewComboBoxColumn();
color_name.DataPropertyName = "Color Name";
color_name.HeaderText = "Color Name";
color_name.Name = "color_name";
color_name.Width = 120;
color_name.DataSource = bi2;
color_name.ValueMember = "color_name";
//ColumnItem.DisplayMember = "ItemText";
dataGridView1.Columns.Add(color_name);
//quantity
DataGridViewTextBoxColumn quantity = new DataGridViewTextBoxColumn();
quantity.HeaderText = "Quantity";
quantity.Width = 100;
quantity.DataPropertyName = "Quantity";
quantity.Name = "quantity";
dataGridView1.Columns.Add(quantity);
//Pcs/Carton
DataGridViewTextBoxColumn pcs_carton = new DataGridViewTextBoxColumn();
pcs_carton.HeaderText = "Piece/Carton";
pcs_carton.Width = 100;
pcs_carton.DataPropertyName = "Piece/Carton";
pcs_carton.Name = "pcs_carton";
dataGridView1.Columns.Add(pcs_carton);
//No Of Carton
DataGridViewTextBoxColumn no_carton = new DataGridViewTextBoxColumn();
no_carton.HeaderText = "No Of Carton";
no_carton.Width = 70;
no_carton.DataPropertyName = "No Of Carton";
no_carton.Name = "no_carton";
dataGridView1.Columns.Add(no_carton);
//unit name
DataGridViewComboBoxColumn unit_name = new DataGridViewComboBoxColumn();
unit_name.DataPropertyName = "Unit Name";
unit_name.HeaderText = "Unit Name";
unit_name.Name = "unit_name";
unit_name.Width = 120;
unit_name.DataSource = bi3;
unit_name.ValueMember = "unit_name";
//ColumnItem.DisplayMember = "ItemText";
dataGridView1.Columns.Add(unit_name);
//rate
DataGridViewTextBoxColumn rate = new DataGridViewTextBoxColumn();
rate.HeaderText = "Rate";
rate.Width = 70;
rate.DataPropertyName = "Rate";
rate.Name = "rate";
dataGridView1.Columns.Add(rate);
//amount
DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
amount.HeaderText = "Amount";
amount.Width = 70;
amount.DataPropertyName = "Amount";
amount.Name = "amount";
dataGridView1.Columns.Add(amount);
//Ship quantity
DataGridViewTextBoxColumn ship_qty = new DataGridViewTextBoxColumn();
ship_qty.HeaderText = "Ship Quantity";
ship_qty.Width = 70;
ship_qty.DataPropertyName = "Ship Quantity";
ship_qty.Name = "ship_qty";
dataGridView1.Columns.Add(ship_qty);
#endregion
}
values(#order_no,
(select article_id from article_order where article_name=#article_name),
(select size_id from size where size_name=#size_name),
(select color_id from color where color_name=#color_name),
#quantity,#piece_carton,#no_of_carton,
(select unit_id from unit where unit_name=#unit_name),
#rate,#ship_qty,#date1,#amount)
The error message would show up if any of the marked subselects in your procedure returns more than one value.
Can we see your select query? it seems that there is a subquery that returns more then 1 value
Run this query:
select article_name,COUNT(*) from article_order GROUP BY article_name HAVING COUNT(*)>1
If it returns ANY rows, then your problem is that you have multiple articles in your table with the same name.
Alternatively, make sure that you have a UNIQUE INDEX on each of article_name, color_name, unit_name, and size_name. If you get an error while trying to create that index (because one will definitely give you an error), then you need to fix that in the appropriate table, then create the index.
I have a gridview and Textboxes in Form1. When Form1 loads it will load the data into Gridview from database. I have a selectionChanged event of Gridview from where the data goes into textboxes and Now my problem is I want to edit them in Textboxes and save them to database, but When I click on save button it is creating a new record in the database and gridview. How to fix this ?
Below is my code for SaveButton:
private void btnSave_Click_1(object sender, EventArgs e)
{
DataRow dr = dt.NewRow();
da = new SqlDataAdapter("select * from Measurement", con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
dr["CellNumber"] = txtCellNo.Text.Trim();
dr["FirstName"] = txtFirstName.Text;
dr["LastName"] = txtLastName.Text;
dr["Shirt"] = txtShirt.Text;
dr["Pant"] = txtPant.Text;
dr["DueDate"] = txtDueDate.Text;
dr["Date"] = txtDate.Text;
if (dr["CellNumber"] == "")
{
MessageBox.Show("Please enter Cell Number");
}
else if (dr["CellNumber"] != "")
{
dr = dt.Select(" ID = " + txtID.Text)[0]; //updated here
}
try
{
da.Update(ds, "Measurement");
}
catch (DBConcurrencyException ex)
{
MessageBox.Show(ex.Message);
}
}
Code for Gridview:
private void dgv_SelectionChanged_1(object sender, EventArgs e)
{
if (dgv.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in dgv.SelectedRows)
{
//Send the first cell value into textbox'
txtLastName.Text = row.Cells["LastName"].Value.ToString();
txtFirstName.Text = row.Cells["FirstName"].Value.ToString();
txtCellNo.Text = row.Cells["CellNumber"].Value.ToString();
txtDate.Text = row.Cells["Date"].Value.ToString();
txtDueDate.Text = row.Cells["DueDate"].Value.ToString();
txtPant.Text = row.Cells["Pant"].Value.ToString();
txtShirt.Text = row.Cells["Shirt"].Value.ToString();
txtID.Text = row.Cells["ID"].Value.ToString();
}
}
}
da.Update(ds, "Measurement"); is inserting a new record because the RowState property of the row you are attempting to update is set to Added since you are assigning the cell values to a new row. You need to update the values of an existing row. Check DbDataAdapter.Update Documentation :
When an application calls the Update method, the DbDataAdapter
examines the RowState property, and executes the required INSERT,
UPDATE, or DELETE statements iteratively for each row, based on the
order of the indexes configured in the DataSet
Try this :
private void btnSave_Click_1(object sender, EventArgs e)
{
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from Measurement where ID = #ID",con);
da.SelectCommand.Parameters.AddWithValue("#ID",int.Parse(txtID.Text));
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.Fill(ds, "Measurement");
if (String.IsNullOrEmpty(txtCellNo.Text.Trim()))
{
MessageBox.Show("Please enter Cell Number");
}
else
{
try
{
dr = ds.Tables["Measurement"].Rows[0];
dr["CellNumber"] = txtCellNo.Text.Trim();
dr["FirstName"] = txtFirstName.Text;
dr["LastName"] = txtLastName.Text;
dr["Shirt"] = txtShirt.Text;
dr["Pant"] = txtPant.Text;
dr["DueDate"] = txtDueDate.Text;
dr["Date"] = txtDate.Text;
cb.GetUpdateCommand();
da.Update(ds, "Measurement");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Your missing the WHERE condition in your query
da = new SqlDataAdapter("select * from Measurement WHERE ID = " + txtID.Text, con);
What you should look at is the way you save into the db.
What is happening now is you are inserting a new entity/row in the db instead of updating the one you already loaded.
You are missing the primary key field. The ID. So it will always be a new entity to add not one that exists and needs updating.
da = new SqlDataAdapter("select * from Measurement", con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
dr = dt.Select(" ID = " + txtID.Text)[0];
if (txtCellNo.Text == "")
{
MessageBox.Show("Please enter Cell Number");
}
else if (dr["CellNumber"] != "")
{
dr["CellNumber"] = txtCellNo.Text.Trim();
dr["FirstName"] = txtFirstName.Text;
dr["LastName"] = txtLastName.Text;
dr["Shirt"] = txtShirt.Text;
dr["Pant"] = txtPant.Text;
dr["DueDate"] = txtDueDate.Text;
dr["Date"] = txtDate.Text;
}
try
{
da.Update(ds, "Measurement");
}
catch (DBConcurrencyException ex)
{
MessageBox.Show(ex.Message);
}