Text change in TextBoxes - c#

I have some 32 TextBoxes and 1 "Save" button. What I want is to save the text for only those TextBoxes which have their Texts changed. How can I achieve that? How do I know the text of which TextBoxes have changed?

Personally, I would do it server-side. Assuming you have no data binding involved, you could do something like the following in your ASPX.CS code-behind:
...
private string InitialValue1
{
get { return ViewState[#"IV1"] as string; }
set { ViewState[#"IV1"] = value; }
}
// Repeat for all 32 text boxes.
protected void Page_Load( object sender, EventArgs e )
{
if(!IsPostBack )
{
TextBox1.Text = InitialValue1 = loadText1FromDatabase();
// Repeat for all 32 text boxes.
}
}
protected void MySaveButton_Click( object sender, EventArgs e )
{
if ( TextBox1.Text!=InitialValue1 ) saveText1ToDatabase( TextBox1.Text );
// Repeat for all 32 text boxes.
}
...
Of course, in a real-world-scenario, I would do some looping/array handling instead of writing 32 same functions/properties.

I would recommend using a jQuery function on load to make a fake old data input.
Something like this:
$(document).ready(function (){
$(":text").each(
var newid=$(this).attr("id") + "_old";
var oldvalue=$(this).val();
var formy=$("form");
formy.appendChild("<input type='hidden' name='" + newid +"' value='" + oldvalue +"'>);
})
This way, if you change the number, the function automatically writes the correct number for you.
Then on the server side you can compare the values with something like below :
var inputs = Request.Form.Keys.Where(rs=>rs.Contains("_old"));
foreach (var input in inputs)
{
//check the _old vs the input without the old and do your thing
}

You can detect this on the client side for keypress, or compare the values on post and send over a list of items that changed.
However if you want to do this on the server side, you will have to load up your server data and manually compare it against every textbox.

Use session variables to store the data for every postback and compare the values. If the value of a certain textbox changes then save that otherwise dont save.

You can do using HiddenFields. on page load you can set HiddenFields with original TextBox values.
on save button you can compare HiddenFields value with TextBox value, If HiddenField value does not
match with TextBox value then you can save that TextBox value in DB otherwise not.

Use cookie variables to store the data for every postback and compare the values.

Which version are you using, In case of 3.5 and above i would request you to check on this IPostBackDataHandler. This should help you in achieving what you want.
In previous versions i think you will have to do it only by comparing it with the original text or the least you could use the MERGE keyword
(you will have to modify your db queries) while you are pushing your records into the database.

Related

Int field in Winform does not update null values in SQL Server database using C#

In my Winforms C# application, I have fields with Int data type and they are set to accept null values in SQL Server database (allow nulls).
In the forms I have some textboxes which are bound to those int data type fields. If I don't enter anything while creating a new record, it accepts. If I enter a number in the textbox, it also accepts it, and then if I delete it, it doesn’t accept it anymore and even doesn't allow me to move to the next field.
If I set its value as null or "" through code, it simply ignores and does not even update changes which I made in other non int text fields.
I am using following method to update.
this.Validate();
this.itemsbindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.sBSDBDataSet);
What can I do for the textbox to accept null values?
I have tried following.
IDTextBox.Text = "";
IDTextBox.Text = null;
I have tried following with the help of above solutions (specially Mr. Ivan) and this is how it worked out.
To clear the int field on the form:
IDTextBox.Text = String.Empty;
Then on Designer.cs file of the form, as suggested by Mr. Ivan, I searched for 'IDtextbox.DataBindings.Add' and replaced
this.IDTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.itemsbindingSource, "PictureID", true));
with
this.IDTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.itemsbindingSource, "PictureID", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, ""));
It took me a whole day to search and finally I posted my problem here, and it got solved in 1 hour.
This seems to be one of the WF data binding bugs. I can't say what exactly is causing it, but in order to make it work one should set Binding.NullValue property to "" (empty string, the default is null).
I couldn't find a way to do that in the designer, and also it would be quite annoying to locate all text boxes needed. So I would suggest you the following quick-and-dirty approach. Create a helper method like this:
public static class ControlExtensions
{
public static void FixTextBoxBindings(this Control control)
{
if (control is TextBox)
{
foreach (Binding binding in control.DataBindings)
if (binding.NullValue == null) binding.NullValue = "";
}
foreach (Control child in control.Controls)
child.FixTextBoxBindings();
}
}
and then simply include the following in your form Load event:
this.FixTextBoxBindings();
TextBox dont accept null value.
You can check if it null and set String.Empty;
If(dbValue == null)
{
IDTextBox.Text = String.Empty;
}
else
{
// here set value to your textbox
}

Changing dropdown items text before asp.net autopostback

I am taking over a project in which a client has some annoying issues.
They have a dropdown that autopostbacks on change to place the selected text into a t-sql query. Any value that has an apostrophe is causing an query error due to not being escaped
I do not have access to compiled code, but was hoping to write a quick band-aid fix to on selected changed, before posting replace an apostrophe to a double apostrophe to escape it as it goes into query.
I wrote a javscript ddl.change function that works at changing the text.
This however is not working even though the apostrophe does change into two. I was wondering if someone could help understand why.
I have two thoughts of scenarios causing the issue.
On autopostback, it triggers before javascript change function does, therefore passing the original value before javascript has a change to modify it.
The server side code only understands what it originally placed into the dropdown and therefore no matter how much I manipulate the client code, it will only see what it placed?
Can anyone confirm either of these scenarios?
Help would be appreciated!
EDIT: I REVERSE ENGINEERED THE CODE, YES ITS VERY UGLY (AND SQL INJECTABLE) BUT IS NOT MINE AND I CANNOT MODIFY IT
C# Code
protected void ddls_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ddls.SelectedIndex == 0)
{
this.pnlA.Visible = false;
}
else
{
this.pnlA.Visible = true;
string text = Common.GetSql("~/Sql/" + this._Conn + "/PropertyAddressReverseSearch.sql", false, true).Split(new char[]
{
Conversions.ToChar(this._Delimiter)
})[4];
text = string.Concat(new string[]
{
"SELECT * FROM (",
text,
") a WHERE StreetName='",
this.ddls.SelectedItem.Text,
"' "
});
this.Bind(this.ddla, text);
this.ddla.Items.Insert(0, new ListItem("I'm not sure of the house number...", Conversions.ToString(-1)));
this.ddla.Items.Insert(0, new ListItem("", Conversions.ToString(0)));
this.map.Visible = false;
}
}
Javscript + Control
<asp:dropdown runat="server" id="ddls" autopostback="true">
<script type="javascript/text">
$(document).ready(function() {
$("select[id$='adsearch_ddls']").change(function() {
var ddlsValue = $("select[id$='adsearch_ddls'] option:selected").text();
ddlsValue = ddlsValue.replace(/'/g,"\'\'");
$("select[id$='adsearch_ddls'] option:selected").text(ddlsValue);
return false;
});
});
</script>
You can not modify (or add/remove) the Select/dropdown list items client-side, and simply get the same server-side items, with ASP.NET Webforms when viewstate is enabled.
Unless you send back the modified items in another way, like for example in this answer where list items are copied to a hidden field:
function SaveList()
{
//Clear the hidden field
var hField = document.getElementById('<%= YourHiddenField.ClientID %>');
hField.value = '' ;
var selectedList = document.getElementById('<%= YourDropDownList.ClientID %>')
for(i = 0; i < selectedList.options.length; ++i)
{
hField.value = hField.value + ',' + selectedList.options[i].value;
}
That is, assuming by "On selected index change calls server side code" you mean a postback is triggered?
Disabling the ViewState will cause other problems (like SelectedIndexChanged not triggering, etc).
You could handle the selection change through your own (AJAX) postback. But the difference between server- and client-side list items would still remain.

Regarding dropdown list selection

I am bit new in asp.net so please forgive me if my question is silly.
Actually I am loading a page(aspx) through window.open. Everything thing is going fine window is coming with the requested page.
This page is having two panels in a same row ie. in two td's.
One panel is for showing data from different kind of source and the other one is for different kind of source.
Now my problem is with this dropdowns. In my page m having around 10 dropdowns, 5 is left side and 5 is for right side.
when I am setting the values to these dropdowns for both side ( left column 5 dropdowns with differnt values and rith column 5 dropdowns with different values).
i have two seperate methods for "selected vlues" for these dropdowns for each side.
Now problem is........whichever method i call last........that values are appearing in the both side of dropdowns. though i used different methods for selecting values.
see the code snippet of the pageload calls...
if (!IsPostBack)
{
// methods for filling all dropdowns-----
FetchData(); // for first side
FetchData_Q2(); // second side
}
private void FetchData()
{
ddlCardType.SelectedValue = "2";
ddlProductType.SelectedValue = "5";
}
private void FetchData_Q2()
{
ddlCardType.SelectedValue = "1";
ddlProductType.SelectedValue = "1";
}
SO here first side(FetchData()) dropdown is also showing the data as like as second side(FetchData_Q2())
HOPE U R GETTING MY PROBLEM.
It would be better if you could post your code.
But as a suggestion, I would say add the dropdownlist in two different reapter controls, then populate the dropdownlist in the ItemDataBound event of the repeater control.
A better alternative would be to use jQuery like this in each td (or your panel):
for(var i = 0;i<5;i++)
{
var options = $("#options");
$.each(data, function() {
options.append($("<option />").val(this.ID).text(this.Name));
});
//append the $("#options") to a parent div
}
where the data could be achieved by using Ajax GET.
If you want to set selected value for dropdownlist, you have to change selectedindex. You can try something like:
private void FetchData()
{
ddlCardType.SelectedIndex = ddlCardType.Items.IndexOf(ddlCardType.Items.FindByValue("2"));
ddlProductType.SelectedIndex = ddlProductType.Items.IndexOf(ddlProductType.Items.FindByValue("5"));
}
private void FetchData_Q2()
{
ddlCardType.SelectedIndex = ddlCardType.Items.IndexOf(ddlCardType.Items.FindByValue("1"));
ddlProductType.SelectedIndex = ddlProductType.Items.IndexOf(ddlProductType.Items.FindByValue("1"));
}

create hidden textbox, change it value in javascript and get new value. c#

I'm create a web custom control with hidden field:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
hidden = new HtmlInputHidden();
hidden.ClientIDMode = System.Web.UI.ClientIDMode.Static;
hidden.ID = this.ID + "_hidden";
this.Controls.Add(hidden);
}
I change it value in javascript on the page:
$(textbox).text("some text");
Then try to get this value:
string str = Request.Form[hidden.Name];
I get a null.... Also I tryed:
string str = Request.Form[hidden.ClientID]
and still get null.
Thanks.
So when accessing it from JavaScript you need to use this syntax:
$('#field_hidden').val("some text");
further, with the edit, I just noticed that you're not giving it a name as karaxuna stated. And finally, you'd need to make sure it's inside the form tag for it to be part of the Request.Form.
One other way of accessing its value though, even if it's built dynamically inside the Load, is to grab its value with the Value property. However, make sure you do that after the Load, in something like PreRender, because ASP.NET needs to have a chance to bind its value with ViewState.
Give it a name if you want to get it with Request.Form

How do I add a reference to a generated TextBox in the control tree?

I have an input field that is appended to the HTML in a div.
I need to have this input field bound to the ctrlmenuItems in the system but I don't know how.
I have this function which is the one calling the object:
protected void btnSave_Click(object sender, EventArgs e){
int Id = int.Parse(Request.QueryString["edit"]);
DA.page itmToEdit = DA.page.StaticGetById(Id);
itmToEdit.title = ctrltitle.Text;
itmToEdit.menuItems = ctrlmenuItems.Text;
itmToEdit.content = ctrlcontent.Text;
itmToEdit.Update();
UpdateGUI();
pnlEditArea.Visible = false;
}
I tried using:
protected global::System.Web.UI.WebControls.TextBox ctrlmenuItems;
which just creates a null reference.
I tried calling this onInit():
TextBox ctrlmenuItems = new TextBox();
ctrlmenuItems.ID = "ctrlmenuItems";
ctrlmenuItems.Text = "Enter your name";
this.form1.Controls.Add(ctrlmenuItems);
with no luck.
The appending is done like this:
litMenu.Text += string.Format(#"<div>
<a class='button' href='?del={1}'>Slet</a>
<input name='ctrlmenuItems' type='text' id='ctrlmenuItems' value'{0}' />
</div>",
itm.menuItems,
itm.id);
I need to be able to click "save" and it passes on the value from the textField to dataAccess
but I can't figure out how to bind this "virtual" textbox correctly.
input tags with a name attribute will be stored in the Request.Form array when the page posts back.
Whether you add the TextBox control manually, or simply insert the corresponding HTML (which I would not recommend, building HTML via string concatenation makes it very easy to yield invalid HTML), you can retrieve the value when your button is clicked using the following:
string value = Request.Form["ctrlmenuItems"];

Categories

Resources