TextChangedEvent does not fire when textbox changes or not - c#

I am having a difficult time pinpointing what am I doing wrong here. My logic is to run the stored procedure (UpdateRate) only if a textbox changes. If there is no change in the textbox, just skip the stored procedure for that row of information and move to the next one.
Can someone please help me figure this out? I have tried everything. Keep in mind that I am new at this and might not fully understand complicated answers.
C#:
public partial class MainWindow :
{
internal static string oldAvgRate;
internal static string oldOTRate;
internal static string ratetype;
internal static string rtOT;
public MainWindow()
{
InitializeComponent();
string connectionString = "datasource=;port=;username=;password=";
string sDate = DateTime.Now.ToString("yyyy-MM-dd");
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand avgRate = new MySqlCommand("Select ID, DateFrom, DateTo, RateType, Amount, Description from Daily.Rates where RateType = 'Average Hourly Wages' and DateTo >= #sDate", connection);
avgRate.Parameters.Add(new MySqlParameter("sDate", sDate));
MySqlCommand otRate = new MySqlCommand("Select ID, DateFrom, DateTo, RateType, Amount, Description from Daily.Rates where RateType = 'Average OT Hourly Wages' and DateTo >= #sDate", connection);
otRate.Parameters.Add(new MySqlParameter("sDate", sDate));
try
{
connection.Open();
MySqlDataReader AvgR = avgRate.ExecuteReader();
while (AvgR.Read())
{
txtAHW.Text = AvgR["Amount"].ToString();
dfAHW.Text = AvgR["DateFrom"].ToString();
dtAHW.Text = AvgR["DateTo"].ToString();
txtcommAHW.Text = AvgR["Description"].ToString();
oldAvgRate = txtAHW.Text = AvgR["Amount"].ToString();
ratetype = AvgR["RateType"].ToString();
}
AvgR.Close();
AvgR.Dispose();
MySqlDataReader OtR = otRate.ExecuteReader();
while (OtR.Read())
{
txtOTHW.Text = OtR["Amount"].ToString();
dfOTHW.Text = OtR["DateFrom"].ToString();
dtOTHW.Text = OtR["DateTo"].ToString();
txtcommOTHW.Text = OtR["Description"].ToString();
oldOTRate = txtOTHW.Text = OtR["Amount"].ToString();
rtOT = OtR["RateType"].ToString();
}
OtR.Close();
OtR.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
private string UpdateRate(string dateFrom, string newRate, string oldRate, string ratetype, string description)
{
string connectionString = "datasource=;port=;Initial Catalog='';username=;password=";
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
connection.Open();
MySqlCommand cmd = new MySqlCommand("UpdateRate", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p_DateFrom", MySqlDbType.Date).Value = dateFrom;
cmd.Parameters.Add("#p_NewAmount", MySqlDbType.Decimal).Value = newRate;
cmd.Parameters.Add("#p_OldAmount", MySqlDbType.Decimal).Value = oldRate;
cmd.Parameters.Add("#p_RateType", MySqlDbType.VarChar).Value = ratetype;
cmd.Parameters.Add("#p_Description", MySqlDbType.VarChar).Value = description;
cmd.ExecuteNonQuery();
connection.Close();
return newRate;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
private bool txtAHWHasChangedFlag;
private bool txtOTHWHasChangedFlag;
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
var control = sender as TextBox;
if (control.Name == "txtAHW" )
txtAHWHasChangedFlag = true;
else if (control.Name == "txtOTHW")
txtOTHWHasChangedFlag = true;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAHWHasChangedFlag) //True regardless if changes are made in the textbox or not :(
{
oldAvgRate = UpdateRate(dfAHW.SelectedDate.Value.ToString("yyyy-MM-dd"), txtAHW.Text, oldAvgRate, ratetype, txtcommAHW.Text);
MessageBox.Show("Done", "Test", MessageBoxButton.OK);
}
if (txtOTHWHasChangedFlag) //True regardless if changes are made in the textbox or not :(
{
oldOTRate = UpdateRate(dfOTHW.SelectedDate.Value.ToString("yyyy-MM-dd"), txtOTHW.Text, oldOTRate, rtOT, txtcommOTHW.Text);
MessageBox.Show("Done", "Test", MessageBoxButton.OK);
}
if (!txtAHWHasChangedFlag && !txtOTHWHasChangedFlag)
{
MessageBox.Show("Nothing has changed", "Test", MessageBoxButton.OK);
return;
}
}
}
XAML:
<TextBox x:Name="txtAHW" TextChanged="textChangedEventHandler"/>
<TextBox x:Name="txtOTHW" TextChanged="textChangedEventHandler"/>
I have set 2 breakpoints inside inside btnSave_Click on the if statements, started the solution, changed one of the textboxes and notice that whatever I do, both statements result in True. Even if I disable my textboxes and click on the save button, I still get True instead of False. When I attempt to debug I notice the following error on the TextChangedEvent, for one of the textboxes that I change:
I would really appreciate any suggestion. Thank you!
Attempt based on #user2107843 answer. It solves my initial problem, but when I click save the second time, it runs both stored procedures instead of only the one that as changed. So if I change txtAHW and then click save, it works, it only runs the stored procedure for txtAHW. If right after that I change txtOHW as well, the stored procedure runs for both instead for running only for txtOHW. My logic here is that txtAHW has already been saved so no need to run again. Can some help me improve this:
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
var control = sender as TextBox;
if (control.Name == "txtAHW")
if (oldAvgRate != txtAHW.Text && oldAvgRate != null)
txtAHWHasChangedFlag = true;
else
txtAHWHasChangedFlag = false;
else if (control.Name == "txtOTHW")
if (oldOTRate != txtOTHW.Text && oldOTRate != null)
txtOTHWHasChangedFlag = true;
else
txtOTHWHasChangedFlag = false;
}

You should make false in textChangedEventHandler
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
var control = sender as TextBox;
if (control.Name == "txtAHW" )
if(oldAvgRate != txtAHW.Text && oldAvgRate !=null)
txtAHWHasChangedFlag = true;
else
txtAHWHasChangedFlag = false
else if (control.Name == "txtOTHW")
txtOTHWHasChangedFlag = true;
}

Related

Check if textbox or datepicker has changed before running stored procedure C#

I am seeking an easy way to check if a textbox or a datepicker has changed since the form was opened. If it did then run stored procedure, else just skip it and run the ones have have changed.
What I have:
internal static string oldAvgRate;
internal static string oldOTRate;
internal static string ratetype;
internal static string ratetypeOT;
private string UpdateRate(string dateFrom, string newRate, string oldRate, string ratetype, string description){
string connectionString = "datasource=;port=;username=;password=";
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
connection.Open();
MySqlCommand cmd = new MySqlCommand("UpdateRate", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p_DateFrom", MySqlDbType.Date).Value = dateFrom;
cmd.Parameters.Add("#p_NewAmount", MySqlDbType.Decimal).Value = newRate;
cmd.Parameters.Add("#p_OldAmount", MySqlDbType.Decimal).Value = oldRate;
cmd.Parameters.Add("#p_RateType", MySqlDbType.VarChar).Value = ratetype;
cmd.Parameters.Add("#p_Description", MySqlDbType.VarChar).Value = description;
cmd.ExecuteNonQuery();
connection.Close();
return newRate;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
oldAvgRate = UpdateRate(dfAvgR.SelectedDate.Value.ToString("yyyy-MM-dd"), txtAvgR.Text, oldAverageRate, ratetype, txtdescriptionAvgR.Text);
oldOTRate = UpdateRate(dfOTR.SelectedDate.Value.ToString("yyyy-MM-dd"), txtOTR.Text, oldOTRate, ratetypeOT, txtdescriptionOTR.Text);
}
For example: if txtAvgR.Text and/or df.AvgR.Value has changed then run oldAvgRate else skip and run oldOTRate if txtOTR.Text and/or df.OTR.Value has changed else don't run any of them and display MessageBox("Nothing has changed").
How can I achieve this? What's the best approach in my case? Thank you.
Update based on suggestion from #Picnic8 and #Robert Harvey:
XAML:
<TextBox x:Name="txtAvgR" TextChanged="textChangedEventHandler" IsEnabled="False"/>
<TextBox x:Name="txtOTR" TextChanged="textChangedEventHandler" IsEnabled="False"/>
C#:
private bool hasChangedFlag;
// TextChangedEventHandler delegate method.
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
hasChangedFlag = true;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (hasChangedFlag)
{
oldAvgRate = UpdateRate(dfAvgR.SelectedDate.Value.ToString("yyyy-MM-dd"), txtAvgR.Text, oldAvgRate, ratetype, txtdescriptionAvgR.Text);
oldOTRate = UpdateRate(dfOTR.SelectedDate.Value.ToString("yyyy-MM-dd"), txtOTR.Text, oldOTRate, ratetypeOT, txtdescriptionOTR.Text);
MessageBox.Show("Done", "Test", MessageBoxButton.OK);
}
else
{
MessageBox.Show("Nothing has changed", "Test", MessageBoxButton.OK);
return;
}
}
Based on what #Robert Harvey suggested, here is a way to implement the flag.
UPDATED
private bool txtAvgRHasChangedFlag;
private bool txtOTRRHasChangedFlag;
// TextChangedEventHandler delegate method.
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
var control = sender as TextBox;
if (control.Name == "txtAvgR")
txtAvgRHasChangedFlag = true;
else if (control.Name == "txtOTR")
txtOTRHasChangedFlag = true;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAvgRHasChangedFlag)
{
oldAvgRate = UpdateRate(dfAvgR.SelectedDate.Value.ToString("yyyy-MM-dd"), txtAvgR.Text, oldAvgRate, ratetype, txtdescriptionAvgR.Text);
MessageBox.Show("Done", "Test", MessageBoxButton.OK);
}
if (txtOTRRHasChangedFlag)
{
oldOTRate = UpdateRate(dfOTR.SelectedDate.Value.ToString("yyyy-MM-dd"), txtOTR.Text, oldOTRate, ratetypeOT, txtdescriptionOTR.Text);
MessageBox.Show("Done", "Test", MessageBoxButton.OK);
}
if (!txtOTRRHasChangedFlag && !txtAvgRHasChangedFlag)
{
MessageBox.Show("Nothing has changed", "Test", MessageBoxButton.OK);
return;
}
}
Now in your XAML simply reference this event delegate like this
<TextBox x:Name="txtAvgR" TextChanged="textChangedEventHandler" IsEnabled="False"/>
<TextBox x:Name="txtOTR" TextChanged="textChangedEventHandler" IsEnabled="False"/>

Refresh DataGridView after INSERT into SQL

I got my form "InsertClient" and I have the button click method
public void Insert_Button_Click(object sender, EventArgs e)
{
MyClass.InsertNewClient(fullNametxt.Text, shortNametxt.Text);
fullNametxt.Clear();
shortNametxt.Clear();
fullNametxt.Focus();
GridView.Update();
GridView.Refresh();
}
My class recieve this:
public static void InsertNewClient (String fullName, String shortName)
{
SqlConnection conn = DBClass.ConnectionString.GetConnection();
SqlCommand cmd = new SqlCommand("MyStoredProcedure", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#fullName", fullName);
cmd.Parameters.AddWithValue("#shortName", shortName);
int i = cmd.ExecuteNonQuery();
if (i == 0)
{
MessageBox.Show("Can't save data");
}
if (i > 0)
{
MessageBox.Show("Data saved!");
}
}
The thing is, the data is saved but that the DataGridView does not refresh after each INSERT (button click). I have to close the form and re-open it and appears refreshed.
Please help, I want the DataGridView refresh after INSERT data
cCUSTOMERBindingSource Is the object of my BindingSource generated using ToolBox.
public void ReloadGrid()
{
Cursor.Current = Cursors.WaitCursor;
cCUSTOMERBindingSource.DataSource = bd.C_CUSTOMER.ToList();
Cursor.Current = Cursors.Default;
}
this where I called the method
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
C_CUSTOMER cst = new C_CUSTOMER();
C_ACCOUNT acc = new C_ACCOUNT();
cst.FIRST_NAME = txtFname.Text;
cst.MIDDLE_NAME = txtMname.Text;
cst.LAST_NAME = txtLname.Text;
cst.LOCATION = txtlocation.Text;
cst.DATE_OF_BIRTH = Convert.ToDateTime(dateTimePicker1.Text);
acc.ACCOUNT_BALANCE = Convert.ToInt32(txtInitAmoun.Text);
acc.ACCOUNT_NUMBER = Convert.ToInt32(txtAccNumber.Text);
cst.TELEPHONE = Convert.ToInt32(txtTelephone.Text);
cst.DATE_CREATE = DateTime.Now;
int newID = cstDao.insertCustomer(cst.FIRST_NAME, cst.MIDDLE_NAME, cst.LAST_NAME, cst.LOCATION, cst.DATE_OF_BIRTH, cst.TELEPHONE, cst.MODIFY_BY, cst.DATE_MODIFY, cst.DATE_CREATE);
acc.CUSTOMER_ID = newID;
acc.DATE_CREATED = DateTime.Now;
acc.CREATED_BY = 1;
int newAccID = cstDao.insertAccount(acc);
if(newID != 0 && newAccID != 0) {
MessageBox.Show("Insert Succefull", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Error during the insertion", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ReloadGrid();
}
On Form load
private void Form3_Load(object sender, EventArgs e)
{
bd = new Customer_DBEntities();
cCUSTOMERBindingSource.DataSource = bd.C_CUSTOMER.ToList();
}
You should have separate method for example Refresh() which in your case will obtain data from sql using sqlDataReader and after your insertBtn call that method and initialize dataGridView DataSource to it
Something like that #mmking, but not exactly
I already solved it.. the problem was exactly what #Fabio said...
Inside of the button click method I fill again de DataGridView with the DataSet.
public void Insert_Button_Click(object sender, EventArgs e)
{
MyClass.InsertNewClient(fullNametxt.Text, shortNametxt.Text);
this.tblClientTableAdapter.Fill(this.DataSetClient.tblClient);
}
Just to get clear... I use the DataGridView of toolbox, select "Choose data source" and select the table that I want to use to fill DataGrid...
I use the DataSetName that gave me by default and put it right like I show it in the code
Hope it helps for future questions

Public variable loses value on button click event asp.net

I have checkboxes in my asp.net gridview and I have a method to select multiple checkboxes and that works great. After that when the user inputs a value in the textbox to be updated to the rows selected the values I just set are null again? I have included my method of checking multiple items and my update button. Why are the values not being retained and how can I fix it?
public variables
public string values = "";
public string salesorderNumber;
Multiple checkboxes
protected void SelectCheckBox_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chk = sender as CheckBox;
var rows = dropdeadGridView.Rows;
int count = dropdeadGridView.Rows.Count;
for (int i = 0; i < count; i++)
{
bool isChecked = ((CheckBox)rows[i].FindControl("SelectCheckBox")).Checked;
if (isChecked)
{
values += rows[i].Cells[1].Text + ",";
rows[i].BorderColor = System.Drawing.Color.Red;
rows[i].ForeColor = System.Drawing.Color.Red;
rows[i].BorderStyle = BorderStyle.Inset;
}
}
}
Update Button
protected void UpdateButton_Click(object sender, EventArgs e)
{
App_Code.GridData gridData = new App_Code.GridData();
if (loadnumTextBox.Text == "" && RadDateTimePicker1.SelectedDate != null)
{
SqlConnection dbConn = App_Code.DBHelper.getConnection();
try
{
using (dbConn)
{
SqlCommand addJob = new SqlCommand(#"UPDATE ORDER_DETAIL SET DropDeadTime = #DropDeadTime WHERE SALES_ORDER_NUMBER = #SalesOrderNumber", dbConn);
//addJob.Parameters.AddWithValue("#SalesOrderNumber", Convert.ToInt32(IDTextBox.Text));
addJob.Parameters.AddWithValue("#SalesOrderNumber", values);
addJob.Parameters.AddWithValue("#DropDeadTime", RadDateTimePicker1.SelectedDate);
dbConn.Open();
addJob.ExecuteNonQuery();
}
NotificationLabel.Text = "Updated!";
NotificationLabel.Visible = true;
}
catch (Exception ex)
{
throw ex;
}
BindList();
}
if (loadnumTextBox.Text != "" && RadDateTimePicker1.SelectedDate == null)
{
SqlConnection dbConn = App_Code.DBHelper.getConnection();
try
{
using (dbConn)
{
SqlCommand addJob = new SqlCommand(#"UPDATE ORDER_DETAIL SET LOAD_NUMBER = #LOAD_NUMBER WHERE SALES_ORDER_NUMBER = #SalesOrderNumber", dbConn);
addJob.Parameters.AddWithValue("#SalesOrderNumber", salesorderNumber);
addJob.Parameters.AddWithValue("#LOAD_NUMBER", loadnumTextBox.Text);
dbConn.Open();
addJob.ExecuteNonQuery();
}
NotificationLabel.Text = "Updated!";
NotificationLabel.Visible = true;
}
catch (Exception ex)
{
throw ex;
}
BindList();
}
If you want it to live between requests you'll have to use something like session-state, view-state, a cookie, or a HTML form / request value.
ASP.NET is stateless meaning it does not keep it state from post back to postback.
You need a static one if you want to achieve your goal.

c# databinding modifying grid values

I have a crud form with a datagridview.
Here's my "refresh" code:
private void Recuperar()
{
DataSet ds = new DataSet();
string CommandText = "SELECT * from sectores order by sector";
SQLiteDataAdapter adapter = new SQLiteDataAdapter(CommandText, Variables.Conexion);
DataTable table = new DataTable();
table.TableName = "sectores";
adapter.Fill(table);
grilla.DataSource = table;
grilla.Refresh();
grilla.Columns["sector_id"].Visible = false;
grilla.Columns["clave"].Visible = false;
grilla.Columns["sector"].HeaderText = "Sector";
grilla.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
SetDataBinding();
}
private void SetDataBinding()
{
this.textBoxId.DataBindings.Clear();
this.textBoxId.DataBindings.Add(new System.Windows.Forms.Binding("Text", grilla.DataSource, "sector_id"));
this.tbSector.DataBindings.Clear();
this.tbSector.DataBindings.Add(new System.Windows.Forms.Binding("Text", grilla.DataSource, "sector"));
this.tbClave1.DataBindings.Clear();
this.tbClave1.DataBindings.Add(new System.Windows.Forms.Binding("Text", grilla.DataSource, "clave"));
this.tbClave2.DataBindings.Clear();
this.tbClave2.DataBindings.Add(new System.Windows.Forms.Binding("Text", grilla.DataSource, "clave"));
}
In the code of my "Add" button, i clear the text of my controls (the controls that are binded to the datagrid), so the user insert the new values.
private void btn_agregar_Click(object sender, EventArgs e)
{
grilla.ClearSelection();
accion = DataRowAction.Add;
SetEstado();
}
private void SetEstado()
{
if (accion == DataRowAction.Add)
btn_guardar.Text = "Agregar";
if (accion == DataRowAction.Change)
btn_guardar.Text = "Modificar";
if (accion == DataRowAction.Delete)
btn_guardar.Text = "Eliminar";
if (accion == DataRowAction.Nothing)
btn_guardar.Text = "Guardar";
groupBoxControles.Enabled = accion == DataRowAction.Add || accion == DataRowAction.Change;
PanelDerechaBotones.Enabled = accion != DataRowAction.Nothing;
panelAbajo.Enabled = accion == DataRowAction.Nothing;
grilla.Enabled = accion == DataRowAction.Nothing;
if (accion == DataRowAction.Add)
{
textBoxId.Text = "0";
tbSector.Text = "";
tbClave1.Text = "";
tbClave2.Text = "";
}
if (accion == DataRowAction.Add || accion == DataRowAction.Change)
{
tbSector.Focus();
}
}
the problem is that when the user cancels this action, the row that was selected in the grid now looks all empty. (moved empty values ​​from the controls to the grid)
I know I'm missing something, but don't know what.
appreciate if someone help me.
Cancel button code
private void btn_cancelar_Click(object sender, EventArgs e)
{
accion = DataRowAction.Nothing;
SetEstado();
//((DataTable)grilla.DataSource).RejectChanges();
}
I am assuming that the cancel button is posting back and you are not rebinding? The grid has to be rebound after every postback.

Error on Delete Last row of DataGridview on Winform Application in c#

I am working in Window application in asp.net. I have a GUI in which user enter a product name and quantity in text boxes. On Add button click i am adding a new row in Datagridview and set the value of productname and quantity in datagridview columns. I am not inserting record in Database and I am only save record in Datatable as well add record in Datagridview.
Problem is that when I select a last row from datagridview and press delete button from keyboard then it generate an error
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
static public DataTable gdt;
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (txtItemCode.Text.Trim() == "")
{
MessageBox.Show("Enter Item Code");
txtItemCode.Focus();
return;
}
if (txtQty.Text.Trim() == "")
{
MessageBox.Show("Enter Qty");
txtQty.Focus();
return;
}
if (Convert.ToInt32(txtQty.Text.Trim()) <= 0)
{
MessageBox.Show("Qty must be greater than 0");
txtQty.Focus();
return;
}
if (btnAdd.Text == "ADD")
{
DataRow[] dr = gdt.Select("Item_Code = '" + txtItemCode.Text.Trim() + "'");
if (dr.Length > 0)
{
MessageBox.Show("Item Code Already Exist.");
txtItemCode.Text = "";
txtItemCode.Focus();
return;
}
tblItemMasterBLL oItem = new tblItemMasterBLL();
int ItemID = 0;
DataTable dt = new DataTable();
dt = oItem.getItemDetailByItemCode(txtItemCode.Text.Trim());
if (dt.Rows.Count > 0)
{
ItemID = Convert.ToInt32(dt.Rows[0]["Item_ID"]);
gdt.Rows.Add();
gdt.Rows[gdt.Rows.Count - 1]["Item_Code"] = txtItemCode.Text.Trim();
gdt.Rows[gdt.Rows.Count - 1]["Item_ID"] = ItemID;
gdt.Rows[gdt.Rows.Count - 1]["Qty"] = txtQty.Text.Trim();
gdt.Rows[gdt.Rows.Count - 1]["Article_Desc"] = Convert.ToString(dt.Rows[0]["Article_Desc"]);
gdt.Rows[gdt.Rows.Count - 1]["Color_Desc"] = Convert.ToString(dt.Rows[0]["Color_Desc"]);
gdt.Rows[gdt.Rows.Count - 1]["Size_Desc"] = Convert.ToString(dt.Rows[0]["Size_Desc"]);
gdt.Rows[gdt.Rows.Count - 1]["MRP"] = Convert.ToString(dt.Rows[0]["MRP"]);
dgv_Items.DataSource = null;
dgv_Items.DataSource = gdt;
}
else
{
MessageBox.Show("Invalid Item Code");
}
txtItemCode.Text = "";
txtQty.Text = "";
}
else if (btnAdd.Text == "UPDATE")
{
if (gdt.Rows.Count > 0)
{
gdt.Rows[Convert.ToInt32(lblhdnRowIndex.Text)]["Qty"] = txtQty.Text.Trim();
dgv_Items.Rows[Convert.ToInt32(lblhdnRowIndex.Text)].Cells["Qty"].Value = txtQty.Text.Trim();
}
txtItemCode.ReadOnly = false;
txtItemCode.Text = "";
txtQty.Text = "";
lblhdnItemID.Text = "";
lblhdnItemCode.Text = "";
lblhdnQty.Text = "";
btnAdd.Text = "ADD";
lblhdnRowIndex.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dgv_Items_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
try
{
if (MessageBox.Show("Do you want to delete the current row?", "Confirm deletion",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
ScrollPosition = 0;
ScrollPosition = dgv_Items.FirstDisplayedScrollingRowIndex;
int iIndex = dgv_Items.CurrentRow.Index;
gdt.Rows.RemoveAt(iIndex);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dgv_Items_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
{
try
{
dgv_Items.DataSource = null;
dgv_Items.DataSource = gdt;
dgv_Items.Rows[dgv_Items.Rows.Count - 1].Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How about ..
ScrollPosition = 0;
dgv_Items.FirstDisplayedScrollingRowIndex=ScrollPosition;
int iIndex = dgv_Items.CurrentRow.Index;
gdt.Rows.RemoveAt(iIndex);
thanks all of u participate to solve my problem. Actually this is index problem.
I have find out the solution In which I have done changes in UserDeletingRow event of Datagridview. I have added a new line in UserDeletingRow eventhich is in bold font. Now my code is working fine.
private void dgv_Items_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
try
{
if (MessageBox.Show("Do you want to delete the current row?", "Confirm deletion",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
ScrollPosition = 0;
ScrollPosition = dgv_Items.FirstDisplayedScrollingRowIndex;
int iIndex = dgv_Items.CurrentRow.Index;
DataRow dr = gdt.Rows[iIndex]; //new added code
gdt.Rows.RemoveAt(iIndex);
gdt.Rows.InsertAt(dr, iIndex); //new added code
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources