failing to update private fields in Asp.net - asp.net

I have a private field in the code behind file of Asp.net page that I'm trying to reset but for some reason it doesn't update. this is the field
private double interest = 0;
I then update this field in this method:
protected void DropDownListBanks_SelectedIndexChanged(object sender, EventArgs e)
{
MajesticEntities majesticentities = new MajesticEntities();
var query2 = from bank in
majesticentities.Banks
where bank.Name == DropDownListBanks.SelectedValue
select bank.Interest;
interest = query2.Single().Value;
// Label5.Text = interest.ToString();
// Label5.Text = fees.ToString() + "welcome";
}
When I try to use the field again in a code initiated by a button click I get the original value (0)
Can anyone please explain why this is happening ?
Thanks

You need to save them in an hidden field , textbox , label or in a view state.
ViewState["VSinterest"] = interest;
Then the value will be saved after postback
"after postback " private double interest = 0; " = 0"
Then if you need te value you take it from where you saved it and convert it to what it needs to be

Related

Check at run time if primary key exists

I am working in asp.net. I have a textbox named formidtxt and another textbox is colortxt. Now what I want is that when a user enters an Form ID in formidtxt then at the same time it should start checking whether there already exists a form id with same ID that has been entered and if Form ID already exists in database then the color of colortxt textbox should change to red else it should be green.
I have an idea that it can be done by using events in text boxes but can't understand the working. My database is in SQL Server 2008.
Try this C# code;
private void Page_Load(object sender, EventArgs e)
{
// formidtxt is the name of the textbox
this.formidtxt.TextChanged += FormIDTextBox_TextChanged;
formidtxt.AutoPostBack = true;
}
Note that this method was written inside the Page_Load method.
TextChanged is an event and it occurs when the text is modified in a TextBox.
In this case, when the formidtxt (textbox) text changes, it will call the FormIDTextBox_TextChanged method.
private void FormIDTextBox_TextChanged(object sender, EventArgs e)
{
int x = 0;
// convert textbox text (string) to int
Int32.TryParse(formidtxt.Text, out x);
// call IsIDAvailableDAO method
// x is the converted int value
if (IsIDAvailableDAO(x))
{
colortxt.BackColor = System.Drawing.Color.Red;
}
else
{
colortxt.BackColor = System.Drawing.Color.Green;
}
}
This method will get the text from the textbox (formidtxt) and send it to the IsIDAvailableDAO method as a parameter.
Using the IsIDAvailableDAO method, we can check whether the ID is available in the database or not. If it is available, then the method will return a TRUE boolean value. If not, it will return a False boolean value.
According to that boolean value, you can change the color of the colortxt textbox as you want or do something else.
private Boolean IsIDAvailableDAO(int id)
{
Boolean output;
using (SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Testing;Integrated Security=True"))
{
string query = #"SELECT CASE WHEN COUNT(ID) >= 1 THEN CAST( 1 as BIT ) ELSE CAST( 0 as BIT )
END As IsAvailable
FROM TableName
WHERE ID = #ID";
SqlCommand cmd = new SqlCommand(query, myConnection);
cmd.Parameters.AddWithValue("#ID", id);
myConnection.Open();
output = (Boolean)cmd.ExecuteScalar();
myConnection.Close();
}
return output;
}
In this method (IsIDAvailableDAO), Please change the query (TableName, ID, etc.) and connectionstring as appropriate.
You also has to add this namespace: using System.Data.SqlClient;
https://www.connectionstrings.com/sql-server-2008/
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/using-namespaces

ASP.NET / Sharepoint - Checkbox.CheckChanged event fires same Event of other (same) control from bevore

I'm working on a Webpart for SharePoint with ASP.NET
On every click my page will be reloaded and I add a List of Checkboxes with different ID's in two tables and a event to handle the CheckedChanged Event (all the same).
In Addition the autopostback is set to true.
When I run and click my first checkbox every thinks work fine.
By clicking the next checkbox in the same table, I get in my eventReceiver 2! Events - first, the right one and after that the checkbox was clicked before.
As many boxes I click, as many checkboxes fire their Event (when used before).
Only difference is between the 2 Tables. Here clicking in first table all is ok, clicking in second table all ok... after that each table has the same effect. Click in first table again, I get 2 Events to handle, click in the second one these 2 to handle.
I have no idea what's going wrong.
Here's some code
CheckBox eMailNotifikation = new CheckBox() { TextAlign = TextAlign.Right };
eMailNotifikation.ID = #anCounter + "_" + #anName + "_" + #anothername + "_" + "mail_checkbox";
eMailNotifikation.AutoPostBack = true;
eMailNotifikation.CheckedChanged -= new EventHandler(eMailNotifikation_CheckedChanged);
eMailNotifikation.Checked = #setInitialValue;
//Add Event
eMailNotifikation.CheckedChanged += new EventHandler(eMailNotifikation_CheckedChanged);
cell.Controls.Add(eMailNotifikation);
that's it for creation
here's my receiver:
void eMailNotifikation_CheckedChanged(object sender, EventArgs e) {
CheckBox eMailNotification = (sender as CheckBox);
//Do some... calling a Webservice
eRoomWebservice.DoMyTasl(<params>);
}
the tables are only build with new... and ID.. nothing Special
EDIT::::
I've build the code in easy ASP.NET and there it is working, maybe this is a SharePoint Issue
protected void Page_Load(object sender, EventArgs e) {
Table test = new Table();
test.ID = "test1";
TableHeaderRow thr = new TableHeaderRow();
TableHeaderCell thc = new TableHeaderCell();
thc.Text = "Checkboxes";
thr.Controls.Add(thc);
test.Controls.Add(thr);
TableRow tr = new TableRow();
for (int i = 0; i < 10; i++)
{
TableCell tc = new TableCell();
CheckBox chb = new CheckBox();
chb.ID = "Some_" + i;
chb.AutoPostBack = true;
chb.CheckedChanged += new EventHandler(TestEH);
tc.Controls.Add(chb);
tr.Controls.Add(tc);
}
test.Controls.Add(tr);
root.Controls.Add(test);
}
void TestEH(object sender, EventArgs e) {
CheckBox chbx = sender as CheckBox;
string text = chbx.ID;
}
i found out wha'ts the Problem on my posted issue.
Content of the attribute ID="" was too Long, after shrinking the IDName it was working again.
Strange but it was the solution,
Remember: Watch out how Long Content of the Attribute ID is, there must be a Limit somewhere

Get control which is generated on runtime

am creating some TextBoxes by backend on a text change event, Like this :
protected void txtHowMany_TextChanged(object sender, EventArgs e)
{
int totalSections = Convert.ToInt32(txtHowMany.Text.Trim());
for (int i = 1; i <= totalSections; i++)
{
TextBox tbx = new TextBox();
tbx.Text = "";
tbx.ID = "section" + i;
tbx.Style.Add("width", "90%");
tdSectionsAdd.Controls.Add(tbx);
}
trSectionsName.Visible = true;
}
The auto post back is true for txtHowMany, so when I enter a number, it generates the textboxes and add it to table division
Now the problem is, I am trying to get text from generated textboxes like this :
protected void btnSave_click(object sender, EventArgs e)
{
int numbersOfSectionsToSave = 1;
int sectionsToSave =Convert.ToInt32(txtHowMany.Text.Trim());
for (int i = 1; i < sectionsToSave; i++)
{
Sections section = new Sections();
section.CourseId = result;
section.OrganizationId = course.OrganizationId;
foreach (Control c in tdSectionsAdd.Controls)
{
if (c.GetType() == typeof(TextBox))
{
TextBox txtBox = (TextBox)c;
string id = "section" + i;
if (txtBox.ID == id)
{
section.Name = txtBox.Text.Trim();
}
}
}
string name = Request.Form["section1"];
section.CreatedBy = "Admin";
section.CreationDate = DateTime.Now;
section.ModifiedBy = "Admin";
section.ModificationDate = DateTime.Now;
numbersOfSectionsToSave += section.SaveSection();
}
But its showing 0 count for the controls in tdSectionsAdd , The controls are added before I am trying to access them, but still it shows no controls in td.
Please help, How can I get these textboxes?
Thanks!
You need to add them in each postback. Store the totalSections variable in ViewState so you can add them i page load also:
protected void AddTextBoxes()
{
int totalSections;
if (int.TryParse(Convert.ToString(ViewState["TotalSections"]), out totalSections)
{
for (int i = 1; i <= totalSections; i++)
{
TextBox tbx = new TextBox();
tbx.Text = "";
tbx.ID = "section" + i;
tbx.Style.Add("width", "90%");
tdSectionsAdd.Controls.Add(tbx);
}
trSectionsName.Visible = true;
}
}
protected void txtHowMany_TextChanged(object sender, EventArgs e)
{
ViewState["TotalSections"] = Convert.ToInt32(txtHowMany.Text.Trim());
tdSectionsAdd.Controls.Clear();
AddTextBoxes();
}
protected void Page_Load(object sender, EventArgs e)
{
AddTextBoxes();
}
Dynamic Created controls "Disappear" on postback, if they are not "recreated" in the Page_Init of that page.
Only if they are created in the page_init will the page's viewstate get updated with their information.
Long Explantion:
When we perform a postback (or partial postback) we want to be able to access those controls (or at least the values the user put into them).
We know that the data is in the viewstate, but ASP.NET doesn’t really know which control a ViewState item belongs to. It only knows to match a viewstate item and a control through the same index (e.g. Matches item n in the viewstate tree to item n in the control tree). Therefore in order to get the dynamic controls' data, we need to re-create the controls each time the page is postbacked.
BUT in order for this to work, we need to re-create the controls in the Page_Init function NOT in the Page_Load.
Why? Because when the ViewState is created it needs all the controls to already exist.
This is taken from MSDN, as you can see the viewstate is loaded AFTER the init but before the page load.
TL;DR Call the function that creates the dynamic controls in the page_init and you should be able to see all the values the user entered when the page postbacks
A few links on this issue:
http://forums.asp.net/t/1186195.aspx/1
ASP.NET - Dynamic controls created in Page_Pre_init() or Page_Init() or Page_Load()
Option 2:
I should note: If the controls all had unique Ids and you're not interested in re-creating them again every postback - you could always look for them in the Request Object.
The Request.Form is a NameValueCollection that holds the values of all the controls that were part of the form, just search it for whatever you're looking for

Why ComboBox items need to be reselected to obtain Value?

I am using ext.net 1.3 controls in my ASP.NET 4.0 application. I have several ComboBox controls on my Web Form. The page is supposed to perform two tasks, Insert and Update. There are no issues when a new record is saved, but when I try to fill the ComboBox controls with an existing database values, various issues pop up. The most troubling is this one:
The ComboBox displays the Text from the database, but it neither gets populated nor I am able to pick the ComboBox Value Member. This is because it is not populated. I have written code to populate ComboBox in the Page Load event.
I am using this code to pick a value from the database and show it on the ComboBox:
string Query = "SELECT CustName FROM CustomerMaster WHERE CustID = " + Session["CustomerID"];
var result = DB.Single<Customer>(Query);
CustomerComboBox.setValue = result.CustName;
This code successfully retrieves the Customer Name and displays in the ComboBox. What it is not doing is that it is not selecting from the ComboBox Item List and neither populating the ComboBox.
If I try to retrieve the Value Member of the Text using:
CustomerComboBox.SelectedItem.Value;
it gives error.
To make it work, I need to click on the ComboBox again to make it populate and than I manually select the same customer name from the list to pick the value.
How to get rid of this issue?
-- Edited --
The code to fill ext.net ComboBox is this:
public void FillExtComboList(string ParameterFlag, ComboBox DropDownName)
{
string Query = "";
using (TransactionScope transactionScope = new TransactionScope())
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cncustomer"].ConnectionString.ToString()))
{
con.Open();
SqlDataReader dr;
try
{
if (ParameterFlag == "Customer")
{
Query = "SELECT CustName FROM CustomerMaster";
}
//Check whether the Drop Down has existing items. If YES, empty it.
if (DropDownName.Items.Count > 0)
DropDownName.Items.Clear();
SqlCommand cmd = new SqlCommand(Query, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
Ext.Net.ListItem extLI = new Ext.Net.ListItem();
extLI.Text = dr[0].ToString();
DropDownName.Items.Add(extLI);
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
con.Close();
// RunCustomScript("alert('" + ex.Message.ToString() + "')", callingPageObjectName);
}
} /* End of SQL Connection */
transactionScope.Complete();
} /* End of Transaction Scope */
}
On Page Load event, the ComboBox control is filled with above method.
I don't see an instruction to fill the combo box, only to set its selected value. Arent you missing a CustomerComboBox.DataSource = someList or something like that?
<-- EDIT -->
Sorry, I thought the setValue was the code on your page load...
OK, this is not be the answer to your problem, but an important performance fix.
you should do this when loading the combo:
when executing the SQL Query:
Query = "SELECT CustID, CustName FROM CustomerMaster"
when filling the combo:
Ext.Net.ListItem extLI = new Ext.Net.ListItem();
extLI.Value = dr["CustId"].ToString();
extLI.Text = dr["CustName"].ToString();
DropDownName.Items.Add(extLI);
so when you want to select an item, you just do this:
CustomerComboBox.setValue = Session["CustomerID"];
and avoid going back to the database to get the customer name.
Now, could you share the code you have to handle the combobox click? Since it does fill the combo, it may throw some ligth to us. Also, try adding
CustomerComboBox.DataBind()
And, come to think of it, I see on Page_Load you use "DropDownName" and later on you use "CustomerComboBox". Could that be the problem?
If I understand you correctly try this code:
protected void Page_Load(object sender, EventArgs e) {
FillExtComboList(DropDownName);
// Set value that you want
DropDownName.SetValueAndFireSelect("Test 3");
}
public void FillExtComboList(ComboBox DropDownName) {
try {
//Check whether the Drop Down has existing items. If YES, empty it.
if (DropDownName.Items.Count > 0)
DropDownName.Items.Clear();
for (int i = 0; i < 10; i++) {
Ext.Net.ListItem extLI = new Ext.Net.ListItem();
extLI.Text = "Test " + i;
DropDownName.Items.Add(extLI);
}
} catch (Exception ex) {
// RunCustomScript("alert('" + ex.Message.ToString() + "')", callingPageObjectName);
} /* End of Transaction Scope */
}

Passing Value from textboxes in one webform to texboxes in another webform

am trying to get users to enter some details into a textbox in form1 and get the entry validated against the database. if the entry is correct, form2 loads with other texboxes including the one they made entries into. however i dont want them to make any changes to the textboxes they entered values into previously neither should they have to re-enter the values again.
how do i get the values in the textboxes to move from form1 to form2?
the code below shows what ive done with both forms but the second form dosent display the items in the textboxes when the form is loaded.
first form
protected void Button1_Click(object sender, EventArgs e)
{
string strConn;
strConn = "Provider=MIcrosoft.Jet.OLEDB.4.0;data Source=" +
Server.MapPath("App_Data/test.mdb");
OleDbConnection mDB = new OleDbConnection(strConn);
mDB.Open();
prodSnStr = pSnTextBox.Text;
purDate = Convert.ToDateTime(purDateTextBox.Text);
string dateStr = purDateTextBox.Text;
productClass aProduct = new productClass();
if (aProduct.Prods(mDB, prodSnStr, purDate))
{
Session["ProdSn"] = pSnTextBox.Text;
Session["PurDate"] = purDateTextBox.Text.ToString();
Response.Redirect("Warranty.aspx");
}
else
{
//error message
}
}
form two
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["ProdSn"] != "")
{
pSNoTextBox.Text = Request.QueryString["ProdSn"];
if (Request.QueryString["PurDate"] != "")
{
dateTextBox.Text = Request.QueryString["PurDate"];
}
else
{
//error message to display
}
}
else
{
//error message to display
}
}
eagaerly waiting for your responses..thanks..
In your code you are putting the values on one page into the session:
Session["ProdSn"] = pSnTextBox.Text;
Session["PurDate"] = purDateTextBox.Text.ToString();
However you are trying to read them out on the 2nd page from the Request collection:
if (Request.QueryString["ProdSn"] != "")
{
pSNoTextBox.Text = Request.QueryString["ProdSn"];
if (Request.QueryString["PurDate"] != "")
{
dateTextBox.Text = Request.QueryString["PurDate"];
}
This makes no sense. If you want to use the session, you must also get the values back out from the session object.
Personally I would look into Cross Page postbacks and Server.Transfer combined with Page.PreviousPage. Just make sure you don't set preserveForm parameter to false if using Server.Transfer.
You aren't passing your values as a query string. If you were your Response.Redirect would look like this:
Response.Redirect("Warranty.aspx?ProdSn=something&PurDate=something");
Instead since you are saving these values in a Session variable try this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["ProdSn"] != "")
{
pSNoTextBox.Text = Session["ProdSn"];
if (Session["PurDate"] != "")
{
dateTextBox.Text = Session["PurDate"];
}
else
{
//error message to display
}
}
else
{
//error message to display
}
}
In the button_click of the first form i entered this code
Session["ProdSn"] = pSnTextBox.Text;
Session["PurDate"] = purDateTextBox.Text.ToString();
Response.Redirect("Warranty.aspx?ProdSn=" + Server.UrlEncode(pSnTextBox.Text) +
"&PurDate=" + Server.UrlEncode(purDateTextBox.Text));
and then in the Page_load event of the second form i did this..
string value = Request["ProdSn"];
string value1 = Request["PurDate"];
pSnTextBox.Text = value;
purDateTextBox.Text = value1;
no hassle sustained....easy and perfectly working....
thank for ya'11 helping....
am very grateful
your asp.net page must post your data to second page.
just set your buttons PostBackUrl attribute.
<asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="target.aspx" />
I do not understand while you are making things complex.
When users clicks the button all data will be send to your target page.

Resources