problem with linq to sql update using asp.net textboxes - c#

I have a textbox and a button. On page load I select one column from one row and put its value in the textbox. I have a button click method that updates the same column/row with the value in the textbox.
The problem i'm having is that when I clear the text in the text box, type in new data and hit submit the new text value is not being saved, it uses the old one.
I put a breakpoint at the end of my button click method and it appears that asp.net is sending the old value of the textbox rather than the new one I put in. I'm totally stumped.
This problem persists even if I have viewstate false on the textbox.
Both of my LINQ queries are wrapped in a using statement.
Any Ideas?
Edit: Here is the full code:
protected void Page_Load(object sender, EventArgs e)
{
using (StoreDataContext da = new StoreDataContext())
{
var detail = from a in da.Brands
where a.BrandID == 5
select new
{
brand = a,
};
foreach (var d in detail)
{
txtEditDescription.Text = d.brand.Description;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (StoreDataContext dk = new StoreDataContext())
{
Brand n = dk.Brands.Single(p => p.BrandID == 5);
n.Description = txtEditDescription.Text;
dk.SubmitChanges();
}
}

As you said, in Page_Load you are retrieving the original value into the text box which overwrites any changes.
Yes, Page_Load DOES execute before Button Click (or any other control events) is executed. I'm going to guess you have done Windows Forms development before this, the ASP.Net web forms event model is quite different. Check out the ASP.NET Page Life Cycle Overview.

I figured it out. I should be be using if(!IsPostBack) on the code that originally fills the textbox with its value.
However this makes no sense to me. If the page is loaded and the textbox text gets a value, then you clear this value and try to insert it into the database, it should insert this value and then when the page post back it will fetch the new value from the database and put the value in the textbox.
The way it's actually working makes it seem like it is executing the page load code before the button click code is executed on post back.

just to trace the error,please try to put a label =( lblDescription.Text ) and leave the rest of code as is,put the new value in the textbox (editdescription.text) try it and tell me what you see
foreach (var d in detail)
{
lblDescription.Text = d.brand.Description;
}

Related

Datagridview Button Programming

i am programming a piece of software for a loyalty scheme. I have basically finished all of it. The only thing i am stuck on for ages is programming the buttons for the datagridview which i am using for my redeem offers page. I have gotten it to add a button to the end of each row automatically when you add a new offer but i am clueless on how to program it to recognize each row.
for e.g.)
Row1) Offer 1 is X name and costs Y
Row2) offer 2 is Z Name and costs F
I can only seem to find the ability to program every single button at once and not individual and even so, i need it to work automatically so when i can add a offer i can immediately purchase it. How would i get it to recognize which row i am on?
here is what my form and database looks like.
Picture Of Form - (picture link)
What my database looks like - (picture link)
below ur class
make public int id;
//adding button
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = True;
col.Text = "ADD";
col.Name = "Btn_add";
DataGridView1.Columns.Add(col);
//pass id values here to do functions..
private void Btn_add_Click(object sender, EventArgs e)
{
}
//this gets selected index of selected row value
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
int id = DataGridView1.SelectedRows(0).Cells(0).Value;
}
In Datagrid please bind OfferId in buy button. When press button then automatically gives id onclick event.
You can simply hook into the RowDataBound Event. This event is called, each time a new entry is put into the table. At this point, you can add a button to the tabe and add a custom action/url to the url.

DropDownList.SelectedValue is incorrect after set in PageLoad

I have set selected item of the DropDownList in PageLoad.
protected void Page_Load(object sender, EventArgs e)
{
strSelect2 = "SELECT * FROM [Order] WHERE orderId = '" + selOrder + "'";
cmdSelect3 = new SqlCommand(strSelect2, conNWind);
conNWind.Open();
dtrReader = cmdSelect3.ExecuteReader();
if (dtrReader.Read())
{
DropDownList1.Text = dtrReader["status"].ToString();
}
conNWind.Close();
After that, I have another function to retrieve the ID of the selected item in the DropDownList.
String cmd1 = "Select * from [Status] WHERE statusName = #statusName";
SqlCommand cmdSelectCat = new SqlCommand(cmd1, a);
a.Open();
cmdSelectCat.Parameters.AddWithValue("#statusName", DropDownList1.SelectedValue);
dtrReader = cmdSelectCat.ExecuteReader();
if (dtrReader.Read())
{
statusId = dtrReader["statusId"].ToString();
}
a.Close();
When I choose another item in the DropDownList, I try to print on a label using a function on a button.
Label9.Text = DropDownList1.SelectedIndex.toString();
But the statusId I get is the ID where the DropDownList select upon PageLoad. How can I get the value of the selected item but not the selected item in the page load? Beside's using IsPostBack
The short answer is that you're trying to combine server-side and client-side code. You've got a global setup and load via ASP.Net, then the 'on-change' of the Selection List is doing some kind of postback to call a server-side function.
You're setting it up to do a request to the server, so it reloads the entire page. And resets the selection in the box, too, probably. Or doesn't do anything. Regardless, you have weird functionality because you're trying to mix functionality between client and server.
I suggest you debug through putting a stop point at the start of your Page_Load() and the start point of your function and seeing what exactly the server is doing after you change the value. Most likely you will be surprised at the order of operations.
To do what I think you're trying to do, I think you'll probably have to use either IsPostBack or Javascript. Sorry.
I suggest you look at this post:
ASP.NET DropDownList OnSelectedIndexChanged event not fired
I think that there might be some help for you inside.

Having trouble changing field information based on Dropdown list

I think this issue has a simple solution but I have been banging my head on it for a few days now. I have a web application in which Dynamically gets a list of students from a stored procedure. I want to look at detailed information for each student and subsequent class information. On the Student's Details page, there is a dropdown list that contains all the classes that the student is in and when one is selected, the Community Partner field should be updated.
I am using SelectedIndexChanged method but in order to make it work, I need to set AutoPostBack to True and that causes the page to reload and thus the dropdown list and selected value to reload as well. I have tried several different configurations of this code with no results.
Here is my ascx file
<asp:DropDownList ID="StudentCourses" runat="server"></asp:DropDownList>
And here is my ascx.cs file
protected void Page_PreRender(object sender, EventArgs e)
{
if (Session["StudentID"] != null)
{
int studentId = Convert.ToInt32(Session["StudentID"]);
Student student = studentRepository.GetStudent(studentId);
StudentCourses_SelectedIndexChanged(sender, e);
StudentCommunityPartner.Text = StudentCourses.SelectedItem.Value;
...
And here is my SelectedIndexChanged method
protected void StudentCourses_SelectedIndexChanged(object sender, EventArgs e)
{
IList<KeyValuePair<Course, CommunityPartner>> courseList = studentRepository.GetStudentCourses(Convert.ToInt32(Session["StudentID"]));
StudentCourses.DataSource = courseList;
StudentCourses.DataBind();
int ctr = 0;
foreach (KeyValuePair<Course, CommunityPartner> kvp in courseList)
{
if (ctr < StudentCourses.Items.Count)
{
StudentCourses.Items[ctr].Text = kvp.Key.CourseCode;
StudentCourses.Items[ctr].Value = kvp.Value.PartnerName;
ctr++;
}
else ctr = 0;
}
StudentCommunityPartner.Text = StudentCourses.SelectedItem.Value;
}
I have tried several combinations and I am at a loss as to how to properly change the content on the page without the dropdownlist refreshing every time I do. Thanks for your help, it is much appreciated.
To set a textbox off of a drop down change look here:
set dropdownlist value to textbox in jQuery
If you have more that you want to do, the selected value from the drop down should be kept in the view state on post back. You might try saving that value
var Selected = StudentCourses.SelectedValue;
populate the drop down
and then set the selected value with the saved value
StudentCourses.SelectedValue = Selected;

Unable to delete data from database

I encountered a problem whereby when the user clicked on the delete button, Nothing happens and when I insert breakpoint to check, The selectLocStation is null. Why is it happening? Can anyone kindly solve my doubts about it?
Here are the codes for you to see my Delete codes. Appreciate any helps that were offered.
private void btnDel_Click(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
int selectLocStation = Convert.ToInt32(cbLocStation.SelectedValue);
var DeleteRTiming =
(from delLocStation in Setupctx.requiredtimings
where delLocStation.RequiredLocationStationID == selectLocStation
select delLocStation).SingleOrDefault();
if (DeleteRTiming != null)
{
Setupctx.DeleteObject(DeleteRTiming);
Setupctx.SaveChanges();
cbLocStation.SelectedIndex = -1;
this.Edit_TS_Load(null, EventArgs.Empty);
MessageBox.Show("Selected Required Timing And " +
"The Location Station Has Been Deleted.");
}
}
}
This is the codes that were used to bind.
private void Edit_TS_Load(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
var DeleteRT = (from DelRT in Setupctx.requiredtimings
join locationstationname ls in Setupctx.locationstationnames on DelRT.RequiredLocationStationID equals ls.locationstationID
select ls.locStatname).Distinct().ToList();
foreach (var locstationData in DeleteRT)
{
cbLocStation.Items.Add(locstationData);
}
}
}
How can selectLocStation be null ? it is of type int, are you getting any exception or you mean your object DeleteRTiming is null ? probably its the DeleteRTiming which is null
The simple answer to that the record you are looking in the database against selectLocStation is not there.
You need to put a break point and see what is being held by 'selectLocStation` and then check the database manually if the record exists in the database.
when you bind your control, you must set it in ! IsPostback and persist you with ViewState
If(! IsPostBack)
{
BindYourControl(); //For just first load.
}
Persist with
EnableViewState = true;
In order to don't erase your selected value
If this is a silverlight application then you might want to use
cbLocStation.SelectedItem
Or it is a ASP.Net site and you rebind the data on every pageLoad
Either way you should have an exception because you are trying to convert a null value.
See the method that you have used to bind the combo box
cbLocStation.Items.Add(locstationData);
This will create the combobox with "ValueField" and "TextFiled" with value of the variable "locstationData"
So when you try to get selected value from cbLocStation.SelectedValue ,it will always contain name and so you cannot parse it to integer.
There is another overload for the "Add" Which will accept Value(Id) and Text(Text to display)
cbLocStation.Items.Add(new ListItem(locstationData.locStatname, locstationData.locStatID));
Try to change the binding portion like this

Dynamically added ASP.NET controls not being stored in ViewState

I have an application where I need to add multiple (and nested) controls to a PlaceHolder. The user enters the number of 'weeks', and my application adds a RadSplitter (using the Telerik control set), along with the relevant panes/grids for the weeks. I add these controls using code behind.
This works fine when first binding (when entering the number of weeks, and clicking Submit). But I also need to enable drag and drop functionality between the controls, which causes a postback.
It seems that the number of controls in my placeholder is always '0' on postback, so I'm guessing they are not being stored in the ViewState. Rather than have to readd these on every postback, how can I ensure my controls are stored in the ViewState?
Here's some example code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (plcSplitter.Controls.Count > 0)
plcSplitter.Controls.Remove(plcSplitter.Controls[0]);
var splitter = new Telerik.Web.UI.RadSplitter();
splitter.Width = Unit.Percentage(100);
int noOfWeeks = int.Parse(txtNoOfWeeks.Text);
DateTime dt = new DateTime(2012, 05, 13);
for (int i = 0; i < noOfWeeks; i++)
{
var range = new Common.DateRange(dt.AddDays(-6),dt);
var pane = new Telerik.Web.UI.RadPane();
Label lbl = new Label();
lbl.ID = "lblText";
lbl.Text = range.To.ToShortDateString();
pane.Controls.Add(lbl);
var gv = AddGrid(i);
pane.Controls.Add(gv);
splitter.Items.Add(pane);
var splitLine = new Telerik.Web.UI.RadSplitBar();
splitter.Items.Add(splitLine);
dt = dt.AddDays(-7);
}
plcSplitter.Controls.Add(splitter);
splitter.DataBind();
}
Controls are not stored in the viewstate, only some of control properties can be stored in viewstate. So, on postback you must create these labels again.
Move that logic to create labels from btnSubmit_Click to separate method, call that method on button click and store data needed to recreate labels somewhere (maybe session), then on postback in OnInit method check for that stored data and if there is some labels create it at that event.
Be sure to read this blog post about viewstate :
http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx
and this about creating controls in runtime
http://weblogs.asp.net/infinitiesloop/archive/2006/08/25/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_.aspx
You can store the data necessary to build your controls in the ViewState, but the really important part is that you make sure your controls are built before you try to access them.
Here's a super basic example.
protected void Page_Load(object sender, EventArgs e)
{
BuildControl(GetLabelData());
}
private Tuple<string, string> GetLabelData()
{
if (Page.IsPostBack)
return (Tuple<string, string>)ViewState["MyLabelData"];
else
return new Tuple<string, string>("lblTest", "Test");
}
private void BuildControl(Tuple<string, string> t)
{
Label l = new Label();
l.ID = t.Item1;
l.Text = t.Item2;
ViewState["MyLabelData"] = t;
plcSplitter.Controls.Add(l);
}
protected void bDoSomething_Click(object sender, EventArgs e)
{
Response.Write(String.Format("plcSplitter.Controls.Count:{0}", plcSplitter.Controls.Count));
}
It's also very important to recognize that these controls are being built at the server and if they can be altered by the client you'll need to implement some mechanism of communication for the important bits of info so you can rebuild your controls and then apply any modifications from the client.
For example you are implementing a draggable control, on the client side when you drag you'll need to store the coordinates in a hidden control manually so that can be posted back to the server and you can have that info available when you're rebuilding the controls.
I think the reason those controls are not stored in the ViewState is that they are being added to the page "too late", after the page ViewState is generated. Look at this post:
Last event in page that can still affect a page's viewstate

Categories

Resources