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
Related
I am creating a little ASP.NET app and have a problem with one field value.
I have defined my enum in a class:
class Column
{
public enum Type {
Undefined = 0,
Integer = 1,
ShortDate = 2,
Etc = 3 }
// some other stuff
}
The app contains some controls to enter properties of a column, namely a dropdownlist for choosing the column type and some unimportant others. And when all properties are properly entered, SaveButton in enabled to save the column type info into a listbox. My Default.aspx.cs contains:
private Column.Type selectedType;
protected void Page_Load(object sender, EventArgs e)
{
// fill the ColumnTypeDropDownList (from the Column.Type enum)
if (!IsPostBack)
{
foreach (Column.Type ct in Enum.GetValues(typeof(Column.Type)))
{
ColumnTypeDropDownList.Items.Add(new ListItem(ct.ToString()));
}
}
}
protected void ColumnTypeDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
PrepareToSave();
}
// also called from other controls events, therefore in a separate method
private void PrepareToSave()
{
// control if all needed properties are entered and set the field
if ((ColumnNameTextBox.Text != "") && (ColumnTypeDropDownList.SelectedValue != Column.Type.Undefined.ToString()))
{
foreach (Column.Type ct in Enum.GetValues(typeof(Column.Type)))
{
if (ct.ToString() == ColumnTypeDropDownList.SelectedValue) selectedType = ct;
}
SaveButton.Enabled = true;
}
}
protected void SaveButton_Click(object sender, EventArgs e)
{
ColumnsListBox.Items.Add(selectedType.ToString()); // always writes "Undefined"
}
The problem is that it always writes "Undefined" into the listbox, even though another type was selected from the dropdownlist. I tried to add the item into the listbox inside the PrepareToSave() method and that works correctly, but I need it outside. On the other hand, the condition controlling if any other value than Undefined is selected from the dropdownlist works well. It seems that the field selectedType has the correct selected value only inside the PrepareToSave() method.
AutoPostBack of all the controls is enabled.
Am I missing something about the enums or do you have any tips how to fix it? Thanks.
Your problem is in the line...
ColumnTypeDropDownList.Items.Add(new ListItem(ct.ToString()));
..namely in new ListItem(ct.ToString()). When you use this constructor of the ListItem class, you create an item with Value set to null. Later you compare against the value:
if (ct.ToString() == ColumnTypeDropDownList.SelectedValue) selectedType = ct;
Since Value of each of the items is null, ColumnTypeDropDownList.SelectedValue is also null and your comparison fails. That should be also easily figured out in a debugger.
The correct list item constructor for you is
ListItem listItem = new ListItem(ct.ToString(), ct.ToString());
As an additional issue, you have to call PrepareToSave in SaveButton_Click, since the selectedType field will have lost its value across requests. PrepareToSave will rebuild that value.
That's most probably because of your if condition as pointed below
if ((ColumnNameTextBox.Text != "") && (ColumnTypeDropDownList.SelectedValue != Column.Type.Undefined.ToString()))
{
Instead of ColumnNameTextBox.Text != "" use !string.IsNullOrEmpty(ColumnNameTextBox.Text)
Just another tip:
Use GetNames instead of GetValues in your foreach loop:
foreach (var ct in Enum.GetNames(typeof(Column.Type)))
{
//do your stuff.
}
If you want to use AutoPostBack ...
Add a hidden control to your page.
In your PrepareToSave(); method you just can add the selectetType like yourControlName.Text = ct;
And change your save handler to this ....
protected void SaveButton_Click(object sender, EventArgs e)
{
// Read the value of the hidden control
ColumnsListBox.Items.Add(yourControlName.Text);
}
How can I have an empty item in the bound ComboBox which uses NULL as the value for an Insert or Update?
With the code below, I can manually add the additional row. The column inspector_id is the primary key of an FK relationship. I have to set inspector_id = -1, since C# does not allow an int to be null. However, the insert (or update) fails since there is no inspector_id: -1 in the database.
private void ItemInfo_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'someDBDataSet.inspector' table. You can move, or remove it, as needed.
this.inspectorTableAdapter.ClearBeforeFill = false;
someDBDataSet.inspectorRow newRow = this.someDBDataSet.inspector.NewinspectorRow();
newRow.inspector_id = -1; // Since an int in C# cannot be null
newRow.fullName = "(none)";
newRow.employeeCode = "";
this.someDBDataSet.inspector.AddinspectorRow(newRow);
this.inspectorTableAdapter.Fill(this.someDBDataSet.inspector);
//this.inspectorTableAdapter.ClearBeforeFill = false;
// TODO: This line of code loads data into the 'someDBDataSet.item' table. You can move, or remove it, as needed.
this.itemTableAdapter.Fill(this.someDBDataSet.item);
}
Eureka! Bind to a view, not table.
Bind inspector_idComboBox to a new SQL Server view of the inspector table.
SELECT NULL as inspector_id, '(none)' as fullName, '' as employeeCode
UNION
SELECT inspector_id, fullName, employeeCode
FROM dbo.inspector
Pros:
The (none) item is in the ComboBox
The SelectedItem and text persists when selecting the item.
The SQL view allows a NULL value for inspector_id
No workarounds are needed in the application code. Just fill the DataSet from the view.
Allows more flexibility as the relationship is not bound.
... brilliant!
Another approach is to clear the ComboBox when selecting (none):
private void inspector_idComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (inspector_idComboBox.SelectedValue != null)
if ((int)inspector_idComboBox.SelectedValue == -1)
inspector_idComboBox.SelectedItem = null;
}
Pros:
The correct NULL value is saved to the DataSet and sent on to the database.
No external clear button is needed.
Cons:
Selecting (none) also clears the text. I'd prefer for (none) to stay selected.
After trying various approaches, I initially decided on the following:
private void ItemInfo_Load(object sender, EventArgs e)
{
this.inspectorTableAdapter.Fill(this.someDBDataSet.inspector);
this.itemTableAdapter.Fill(this.someDBDataSet.item);
}
private void noInspector_btn_Click(object sender, EventArgs e)
{
inspector_idComboBox.SelectedItem = null;
}
Rather than adding a dummy item into the ComboBox, I added a (link) button to clear the ComboBox.
Pros:
The ComboBox clears.
The tableAdapter sets item.inspector_id = NULL
Cons:
Other form controls bound to inspector fields remain unchanged (as there is no "empty" inspector row to use).
No text is displayed in inspector_idComboBox when SelectedItem is null. I'd prefer having something like (none) shown in the box.
I want to retrieve data from database on the current logged in SharePoint user and show it on a control in a detailsview. But I really don't know how to achieve that on the best way. This is a code I've tried but it shows null.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
GetEmployeeCv();
}
}
private void GetEmployeeCv()
{
using (var db = new KnowItCvdbEntities())
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
var theEmpl =(from p in db.EMPLOYEES
where p.username == strUserName
select p).FirstOrDefault();
if(theEmpl != null)
{
Image empImg = (Image)DetailsViewShowFullCv.FindControl("imageProfPic");
empImg.ImageUrl = theEmpl.image;
}
}
}
If I want to databind my detailsview like:
Image empImg = (Image)DetailsViewShowFullCv.FindControl("imageProfPic");
empImg.ImageUrl = theEmpl.image;
DetailsViewShowFullCv.DataSource = ??;
DetailsViewShowFullCv.DataBind();
I don't really know how to do it. Anyone out there that can help me out?
a) The DataSource should be the variable which holds the data. In this case it would be theEmpl
b) Run this through the debugger to check if strUserName is what you expect. The LoginName field typically returns the domain and username like "DOMAIN\UserName" so there's a chance that it will return a null (null by default) value if you're only storing the UserName part in the database without the Domain\
c) For Databinding, either change your LINQ query to p.FieldNameToDatabind or know how to write the Databind code in asp markup so that you can actually display the field.
I have a dropdown in my webpage, which always returns the value 0 as the selected index no matter whichever item the user selects. I have populated the dropdown using a DB query. And I am populating in on Page_Load method in my page. The code shown below does the specified work: int danceid;
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDanceDropDown();
}
}
private void PopulateDanceDropDown()
{
DataTable dt = new DataTable();DataRow row = null;
dt.Columns.Add("Did", Type.GetType("System.Int32"));
dt.Columns.Add("DName", Type.GetType("System.String"));
var dancer_dance = (from dd in context.DANCER_AND_DANCE
where dd.UserId == dancerId
select new
{
Value = dd.DanceId,
Text = dd.DanceName
}).ToList();
foreach (var dndd in dancer_dance)
{
row = dt.NewRow();
row["Did"] = dndd.Value;
row["DName"] = dndd.Text;
dt.Rows.Add(row); dances.DataSource = dt;
dances.DataTextField = dt.Columns[1].ToString();
if (!IsPostBack)
{
dances.DataBind();
}
}
protected void changeIndex(object o, EventArgs e)
{
danceid = dances.SelectedIndex;
}
protected void dropthedance(object o, EventArgs e)
{
int danceIDFromDropDown = danceid;
var dancer_dance = from dd in context.DANCER_AND_DANCE
where dd.DanceId == danceIDFromDropDown
select dd;
foreach (var dndd in dancer_dance)
{
context.DANCER_AND_DANCE.DeleteOnSubmit(dndd);
}
try
{
context.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
The line int danceIDFromDropDown = danceid; in the method dropthedance always has the value 0. Pleaseeeeeeeeeeeeee help someone
Are you sure that you want to be using the index as the ID? Typically, you're going to want to set the actual ID from your database as the DataValueField and then you can grab the value that way.
But I also noticed that you grab the index and place it into a variable on the indexchanged event and then you try to use that value in a different method. I'm assuming that danceid is an attribute somewhere not shown here. At any rate, the value isn't persisting through postbacks. Instead of trying to store it in a variable like you would on a desktop application, try adding EnableViewState="True" to your dropdown control. Then get that index on your submit handler directly. Or if you really want to store it in a variable, then try persisting the value of that variable by storing it in the session or caching it, then pull from that cache/session variable when it comes time to actually use the value.
But again, it might be better practice to place the danceid in the listitem object itself. Just the though of basing IDs on item indexes makes me shudder, especially when you populating the list from a database, because what happens when you add a new item to that list in the library and then try to sort them by name... then your indices become useless.
Replace
int danceIDFromDropDown = danceid;
with
int danceIDFromDropDown = dances.SelectedIndex;
It may work.
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;
}