Text field default value overrides user input - c#

I'm setting some default value for my text fields and those fields are in read only mode. When I pass new values to the those fields and submits the form it saved default value not the new one. I have used PostBack function but it's not working. Here is my code,
protected void Page_Load(object sender, EventArgs e)
{
if (! this.IsPostBack)
{
MakeReadControl();
}
}
private void MakeReadControl()
{
((TextBox)this.FindControl("txtMedicalCheckup")).Text = System.DateTime.Now.ToShortDateString();
((TextBox)this.FindControl("txtBosiet")).Text = System.DateTime.Now.ToShortDateString();
((TextBox)this.FindControl("txtLandSurvival")).Text = System.DateTime.Now.ToShortDateString();
((TextBox)this.FindControl("txtDefensiveDriving")).Text = System.DateTime.Now.ToShortDateString();
((DropDownList)this.FindControl("comboDrivingLicense")).SelectedIndex = 1;
((TextBox)this.FindControl("txtOtherLicense")).Text = "Not available";
}
However, the drop down list updates the value correctly.
Update:-
Instead of Read Only attribute if I use enable attribute then it works fine.

Related

How to display selected value-from-dropdownlist-after form submit

I have a dropdown list in my form . After submitting the form I don't get selected value from the dropdown list in UI. I only get first value . How to implement this . How to display dropdown selected value after form submit .
You need to use ViewState or Sessions to save the variable and reuse it, It would look something like this:
private void Page_Load()
{
//If page is not being loaded for first time then set the value another
//option would be to check if ViewState["dropdownvalue"] == null and if
//not then set the value
if (Page.IsPostBack)
{
DropDownList1.SelectedValue = ViewState["dropdownvalue"]
}
}
protected void Submit_Click(object sender, EventArgs e)
{
ViewState["dropdownvalue"] = DropDownList1.SelectedValue;
// Do everything else
}

Data Pager Postback causes value lose

I am new to asp.net. Here is the scenario. I am trying to build a Search functionality. If I enter the value in search box i.e. "Test" and click search icon SQL Server returns results. I have limited datapage size = "1". When I click on next page it refreshes the page and my search box looses the value I entered in this case "Test". If no value is passed SQL Server returns a default result so everytime I navigate through pages it works only for first page each click after that returns me default value. I bind list view on PreRender of datapage. Here are the code snippets.
protected void search_ServerClick(object sender, EventArgs e)
{
mydatapager_PreRender(sender, e);
}
protected void mydatapager_PreRender(object sender, EventArgs e)
{
string var_search_firstname = globalsearchinput.Value.ToString();
string var_search_city = citysearchinput.Value.ToString();
string var_search_state = statesearchinput.Value.ToString();
bool isadvancedsearch = false;
//Determine whether it's advanced search or not.
string MethodCaller = "";
//MethodCaller = ((HtmlButton)sender).ID;
//if (MethodCaller == "search")
//{
// isadvancedsearch = false;
//}
//else
//{
// isadvancedsearch = true;
//}
Utility utl = new Utility();
friendrequestsentnotificationpanel.Visible = false;
listview1.DataSource = utl.SearchProfile(var_search_firstname, var_search_city, var_search_state, isadvancedsearch);
listview1.DataBind();
}
Add ispostback==false condition in preRender. It helps to retain the serch string

Accessing previous value in Hashtable during page refresh

I have a hyperlink field in a gridview. I want to store all the clicked value during a session in a hashtable for that hyperlink field.
protected partial class User : System.Web.UI.Page
{
Hashtable htable = new Hashtable();
int hTableIndex = 0;
// ...
}
In Page Load Function.
if(Session["test"] != null)`
{
for(int i = 0 ; i gvUserStatus.Rows.Count ; i++)
Hashtable tempHashTable = new Hashtable();
tempHashTable = Session["test"] as Hashtable;
if(tempHashTable.Contains(someValue))
{
//Do Something
}
}
In link click event:
protected void userID_Click(object sender, EventArgs e)
{
//logic to get the ClickedValue
if(!htable.Contains(ClickedValue))
{
htable.Add(hTableIndex++,ClickedValue);
}
Session["test"] = htable;
}
I am using the above code, but in my hash table, only the last clicked value is getting stored, what should I do to get all the previous value for an entire user session?
hTableIndex will lose its value upon postback. You will need to store it in Session as well (or just ViewState if you won't need it's value on other pages)
So you need to add this in your Page_Load event:
if (ViewState["hTableIndex"] == null)
ViewState["hTableIndex"] = hTableIndex;
and in your link click event userID_Click
protected void userID_Click(object sender, EventArgs e)
{
//logic to get the ClickedValue
if(!htable.Contains(ClickedValue))
{
var hTableIndex = Convert.ToInt32(ViewState["hTableIndex"]);
htable.Add(hTableIndex++,ClickedValue);
}
Session["test"] = htable;
}
Let me know if this works. Haven't tested it yet.
The problem is within your hTableIndex which will always point to 0 on reloading the page, you also need to put it in the session, so that next time you can get the max value of hTableIndex and add the new link at that index

Asp.net System.ArgumentOutOfRangeException Error with ListBox SelectedIndex

I get this error:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name:index.
Same code was running perfectly in windows form app, but in asp.net i see this error.
My code is here:
public partial class Timeline : System.Web.UI.Page
{
TwitterService servis;
ListBox tweetid = new ListBox();
protected void Page_Load(object sender, EventArgs e)
{
servis = new TwitterService(consumer key,secret,token,token);
tweetid.Items.Clear();
ListBox2.Items.Clear();
IEnumerable<TwitterStatus> anasayfa = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200 });
var gelen = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200, MaxId = anasayfa.Last().Id });
foreach (var tweet in gelen)
{
tweetid.Items.Add(tweet.Id.ToString());
ListBox2.Items.Add(tweet.Text);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
servis.Retweet(new RetweetOptions() { Id = long.Parse(tweetid.Items[ListBox2.SelectedIndex].ToString())});
String uyarı = "alert('Retweetlendi!');";
ClientScript.RegisterOnSubmitStatement(this.GetType(), "ConfirmSubmit", uyarı);
}
}
The problem here is that you have two ListBoxes, one (tweetid) storing the id's (presumably a key of sorts) of the tweets, and the other (ListBox2) storing the text of the tweets. You also don't seem to be adding the dynamically created tweetid ListBox to the page anywhere (and presumably the intention is that the tweetid ListBox is hidden or similar).
You are then attempting to store synchronize the selected text drop down back to the original tweetid in the code behind Button click handler, based on the relative indexes of the data - it is apparant that the two listboxes are getting out of synch, plus, you aren't validating the user has selected a valid item, hence the ArgumentOutOfRange exception.
Although in theory this could be made to work, e.g. by ensuring that the data isn't lost in each page_load roundtrip as per #Dan's answer, and also by enabling ViewState, this all seems rather fragile to me.
I would propose that instead, you use a single ListBox and use the DataTextField to show the tweet to the user, and the DataValueField to track the Id of each tweet:
.aspx
<asp:ListBox runat="server" ID="TweetsListBox" DataTextField="Text" DataValueField="Id" EnableViewState="True" />
.aspx.cs Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Replace with your code to fetch tweets here
TweetsListBox.DataSource = FetchSomeTweets();
// We've alread set the names of the properties to use `Id` and `Text` in the aspx
TweetsListBox.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
long tweetIdToRetweet;
if (long.TryParse(TweetsListBox.SelectedValue, out tweetIdToRetweet))
{
servis.Retweet(new RetweetOptions() { Id = tweetIdToRetweet });
}
else
{
// Display Error that user must select a tweet
}
}
For test purposes, I used the following mock models for your tweet service:
class Tweet
{
public int Id { get; set; }
public string Text { get; set; }
}
private static readonly IEnumerable<Tweet> SomeTweets = new[]
{
new Tweet { Id = 123, Text = "This is tweet 123" },
new Tweet { Id = 234, Text = "This is tweet 234" },
new Tweet { Id = 345, Text = "This is tweet 345" }
};
Your Page_Load method is populating the ListBox everytime the page postback, even before your button click event.
Thus, ListBox2.SelectedIndex will not be the the index that the user selected, since it is freshly populated in the Page_Load method.
You should add a postback check on your page_load and only populate the ListBox if the request is not a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
servis = new TwitterService(consumer key,secret,token,token);
tweetid.Items.Clear();
ListBox2.Items.Clear();
IEnumerable<TwitterStatus> anasayfa = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200 });
var gelen = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200, MaxId = anasayfa.Last().Id });
foreach (var tweet in gelen)
{
tweetid.Items.Add(tweet.Id.ToString());
ListBox2.Items.Add(tweet.Text);
}
}
}

Button on click save objects to database

So I have an event that is when you click a button I want to send an int, string, datetime and bool to my database.
Right now it will get the input from my webform for the "Company" and the "DayNumber". I want to get the value of my CheckBox01 as the boolean for WeatherRain and the input from the Date. You should be able to choose the date not just take it from "now".
I don't know what would be the best way to get this done, I do have around 100 different fields to get user input from.
protected void btnTryck_Click(object sender, EventArgs e)
{
Dagbok bok = DagbokFactory.CreateNew();
bok.Company = String.Format(TextBox1.Text);
bok.DayNumber = Convert.ToInt32(TextBox19.Text);
bok.WeatherRain = false;
bok.Date = DateTime.Now;
}
In order to get the boolean from your CheckBox01 use its Checked property.
bok.WeatherRain = CheckBox01.Checked;
As for the date problem, I'd suggest using a DateTimePicker control to let the user select the date and get its value with the Value property.
Use Checkbox's checked property for this as shown below:
protected void btnTryck_Click(object sender, EventArgs e)
{
Dagbok bok = DagbokFactory.CreateNew();
bok.Company = String.Format(TextBox1.Text);
bok.DayNumber = Convert.ToInt32(TextBox19.Text);
bok.WeatherRain = CheckBox01.Checked;
bok.Date = DateTime.Now;
}

Categories