Public variable loses value on button click event asp.net - c#

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.

Related

How to Edit/Update a row in DataGridView in C#

I m working on a shopping cart like Form in WF. I have a DataGridView an ADD_Button and Submit_Button.The user will choose Items From inventory and Click ADD_ButtonThe item will go into DataGridView After Finishing User will click Submit_Button then detail will go into DB.
Question: is this After adding a product/row into DatagridView When I add same product again.it goes into the new row I want that Where Pro_ID Column Match, The row update with new qty. I tried to search the web but all I got SQL queries.
private void btn_Add_Click(object sender, EventArgs e)
{
i = dgv_Purchase.Rows.Count;
try
{
dgv_Purchase.Rows.Add();
.......
.......
dgv_Purchase.Rows[i - 1].Cells["Pro_ID"].Value = txt_ProID.Text;
.......
.......
dgv_Purchase.Rows[i - 1].Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
catch (Exception ){}
}
This is Submit Button Code
private void btnInsert_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["PRMSConnectionString"].ToString();
SqlConnection con = new SqlConnection(cs);
SqlTransaction objTransaction;
for (int i = 0; i < dgv_Purchase.Rows.Count - 1; i++)
{
//SomeCode part of code
SqlCommand objCmd2;
string cmd2 = "INSERT INTO PurchaseMaster " +
" (Pro_ID , category_ID, Purchase_Qty) " +
"VALUES (#Pro_ID, #category_ID, #Purchase_Qty)";
objCmd2 = new SqlCommand(cmd2, con, objTransaction);
objCmd2.Parameters.AddWithValue("#Pro_ID_ID", dgv_Purchase.Rows[i].Cells["Pro_ID"].Value.ToString());
objCmd2.Parameters.AddWithValue("#Category_ID", dgv_Purchase.Rows[i].Cells["Category_ID"].Value.ToString());
objCmd2.Parameters.AddWithValue("#Purchase_Qty", Convert.ToInt32(dgv_Purchase.Rows[i].Cells["Purchase_Qty"].Value.ToString()));
objCmd2.Parameters.AddWithValue("#Date_Today", Convert.ToDateTime(dgv_Purchase.Rows[i].Cells["Purchase_Date"].Value.ToString()));
...........................
Rest of the Code
...........................
try
{
objCmd2.ExecuteNonQuery();
objTransaction.Commit();
}
catch (Exception) {}
}
}
Try this:
private void AddInfo()
{
// flag so we know if there was one dupe
bool updated = false;
// go through every row
foreach (DataGridViewRow row in dgv_Purchase.Rows)
{
// check if there already is a row with the same id
if (row.Cells["Pro_ID"].ToString() == txt_ProID.Text)
{
// update your row
row.Cells["Purchase_Qty"] = txt_Qty.Text;
updated = true;
break; // no need to go any further
}
}
// if not found, so it's a new one
if (!updated)
{
int index = dgv_Purchase.Rows.Add();
dgv_Purchase.Rows[index].Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
}
I edit it with a DGVrow instead of DataRow
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
if (dr.Cells["Pro_ID"].Value.ToString() == txt_ProID.Text)
{
dr.Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
}

TextChangedEvent does not fire when textbox changes or not

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;
}

dgv selectionchanged c# winforms

Im facing a very weird issue, wich should be very simple.
What im trying to achieve: I have 2 datagrids: 1 with invoiceheaders and 1 with invoiceDetails.
When i click on a particular row from the invoiceheaders, the invoicedetails need to change and show the particular details of that invoice. The event im using for this is dgvInvoiceHeaders_SelectionChanged.
So the code in the view:
private void InvoiceListView_Load(object sender, EventArgs e)
{
int invoiceId = 1;
invoiceHeadersBinding.DataSource = invoiceListPresenter.getInvoiceHeaders();
dgvInvoiceHeaders.DataSource = invoiceHeadersBinding;
setInvoiceHeaderColumns();
if (dgvInvoiceHeaders.CurrentRow != null)
{
Int32.TryParse(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString(), out invoiceId);
}
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(invoiceId);
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
private void dgvInvoiceHeaders_SelectionChanged(object sender, EventArgs e)
{
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(Convert.ToInt32(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString()));
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
And this is the code of the methods im calling:
public List<tbl_invoices> invoiceHeaders;
public BindingList<tbl_invoices> getInvoiceHeaders()
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoice = from i in invoices.tbl_invoices
select i;
invoiceHeaders = invoice.ToList();
var listBinding = new BindingList<tbl_invoices>(invoiceHeaders);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
public List<tbl_invoiceDetail> invoiceDetails;
public BindingList<tbl_invoiceDetail> getSelectedInvoiceDetails(int invoiceID)
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoiceDetail = from i in invoices.tbl_invoiceDetail
where i.InvoiceID == invoiceID
select i;
invoiceDetails = invoiceDetail.ToList();
var listBinding = new BindingList<tbl_invoiceDetail>(invoiceDetails);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
But with this example the formload is loaded correctly. But after the event is fired, my invoiceheader datagrid is empty. When i put the text in comment at the method dgvInvoiceHeaders_selectionChanged(), I see that both of the datagrids are filled correctly.
A push in the right direction would be very kind.

the text of datagridview disappears

i am using telerik control(data grid view) in my project. but when i want to add new row in data grid, the text of previous rows (bindingSourceService.DataSource = dtservice , bindingSourceUnit.DataSource = dtunit) disappear.
my datagridview has 3 combobox column.
what is wrong? please help me.
my codes:
public void FactorLoad(object sender, EventArgs e)
{
try
{
var cb = new CategoriBll();
DataTable dtcategori = cb.GetAllDataCategori();
bindingSourceCategouri.DataSource = dtcategori;
}
catch (Exception ex)
{
ExceptionkeeperBll.LogFileWrite(ex);
}
}
private void DataGridViewFactorCellValueChanged(object sender, GridViewCellEventArgs e)
{
try
{
var row = DataGridViewFactor.CurrentRow;
if ((row != null) && (row.Cells[0].IsCurrent))
{
var categoryId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[0].Value);
var sb = new CategoriOptionBll();
DataTable dtservice = sb.ServiceGetById(categoryId);
bindingSourceService.DataSource = dtservice;
}
if ((row != null) && (row.Cells[1].IsCurrent))
{
var serviceId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[1].Value);
var cbi = new CostBll();
var dtunit = cbi.CostById(serviceId);
bindingSourceUnit.DataSource = dtunit;
}
}
catch (Exception ex)
{
ExceptionkeeperBll.LogFileWrite(ex);
}
}
private void DataGridViewFactorCellEditorInitialized(object sender, GridViewCellEventArgs e)
{
try
{
var row = DataGridViewFactor.CurrentRow;
if ((row != null) && (row.Cells[0].IsCurrent))
{
var categoryId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[0].Value);
var sb = new CategoriOptionBll();
DataTable dtservice = sb.ServiceGetById(categoryId);
bindingSourceService.DataSource = dtservice;
}
if ((row != null) && (row.Cells[1].IsCurrent))
{
var serviceId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[1].Value);
var cbi = new CostBll();
var dtunit = cbi.CostById(serviceId);
bindingSourceUnit.DataSource = dtunit;
}
}
catch (Exception ex)
{
ExceptionkeeperBll.LogFileWrite(ex);
}
}
It will disappear because there will be only 1 value in the data source. Try adding value to the data source rather then assigning single value.

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