Binding database data to a dropdownlist - asp.net

I have been trying for a long time to fix the bugs I'm encountering with my dropdownlists in my project. I'm getting data this with at the moment and it's working fine:
using (InfoEntities ie = new InfoEntities())
{
var sqlddl = (from query in ie.Table_Customers
from q in ie.Accounting_PriceType
where query.TypeID == 1 && q.ID == 1
orderby query.Customers
select query).Distinct().ToList();
DropDownListCust.DataTextField = "Customers";
DropDownListCust.DataValueField = "ID";
DropDownListCust.DataSource = sqlddl;
DropDownListCust.DataBind();
}
Now when the user saves the data and opens the website again I need the saved value that was chosen on the dropdownlist earlier retreived. This also works fine but the problem is I'm getting duplicates. Anyways I'm doing it like this and I'm pretty sure I'm doing it wrong:
On the page load i load my dropdownlist to get all the items plus the following to get the saved value:
DropDownListCust.SelectedItem.Text = sql.Customers;
This makes my DDL very buggy, some items dissapear and also sometimes dupicated values. Can anyone please help? I'm using LINQ but I can use some other methods as long as it's fixed.
Cheers

I solved my problem like this:
DropDownList1.ClearSelection();
DropDownList1.Items.FindByText(sql.Customer).Selected = true;

Related

Image won't display when using session in .NET

I am working with a session and I want to display image when choosing it from a gridview, so what I have two gridviews the first contain the rows from the database the second should contain the rows chosen from the first one the issue that I have is the first display image with no problem but the second won't show up any.
This is my code for the first one
foreach (CONTENT c in ls)
{
string ext = Helper_GetExtensionFromMimeType(c.MimeType);
c.TmpFilename = string.Format("~/Images/Contents/Content-{0}{1}", c.ContentID, ext);
}
gridview1.DataSource = ls;
gridview1.DataBind();
The code for the second one is (the session name is panier)
CONTENT dummy;
dummy = new CONTENT();
dummy.TmpFilename = Server.MapPath(string.Format("~/Images/Contents/Content-{0}{1}",
c.ContentID, ext));
panier.Add(dummy);
gridview2.DataSource = panier;
gridview2.DataBind();
It will be hard to determine what the issue exactly is without seeing your view code.
Anyway, make sure the image indeed exists in the generated location.
Place a breakpoint after the line dummy.TmpFilename and ensure the link is indeed formatted with the correct c.ContentID and ext, then copy the link to the browser making sure the image exists.
i found a solution to the probleme and here it is if anyone is interested
i replace
dummy.TmpFilename = Server.MapPath(string.Format("~/Images/Contents/Content-{0}{1}",c.ContentID, ext));
with
dummy.TmpFilename =string.Format("~/Images/Contents/Content-{0}{1}",c.ContentID, ext);

findcontrol does not find dynamically added control which was just addes one line before

who can explain this to me?
CheckBox ckRequest = new CheckBox();
ckRequest.ID = "ckRequest";
ckRequest.DataBinding += new EventHandler(this.CkIsRequested_DataBinding);
container.Controls.Add(ckRequest);
Control con = container.FindControl("ckRequest");
Debugging shows that con is still null.
Debugging also shows me, that conteiner.Controls hase one Item with ID "ckRequest"
How can this be????
Many thanks for your answers.
Actually I try the following.
findcontrol does not find dynamically created control in rowUpdating eventhandler
It makes sense to me, that findcontrol works only on the created page.
At which point in time the visual tree of the page is created?
FindControl only works when the control is in the visual tree of the page
In your case you can try this
var checkBoxesInContainer = container.Controls.OfType<CheckBox>();
http://msdn.microsoft.com/en-us/library/bb360913.aspx
You can use the following:
Control con =
container.Controls.Cast<Control>().First(item => item.ID == "ckRequest");
You might want to try to following:
//GET THE CHECKBOXLIST
Control c = phCategories.Controls.Cast<Control>().First(item => item.ID == "cblCatID-" + catID && item.GetType().Name == "CheckBoxList");
if (c.GetType().Name == "CheckBoxList")
{
cbl = (CheckBoxList)c;
}
For some reason I needed to cast this as a control first. If I did not do it this way, I seemed to grab a label instead (which didn't make sense to me, because it wasn't actually grabbing a label). Hope it helps somebody.

Add properties to every control with a specific name/pattern in the ID - ASP.NET (VB)

I have several controls on a page that contain the word "DATE" in the ID. These are specific text boxes for dates only.
Here is an example of what I need to do for each text box control with "DATE" in the ID:
Birth_Date.Text = fnLib.formatDate(Birth_Date.Text, 1)
Anniversary_Date.Text = fnLib.formatDate(Anniversary_Date.Text, 1)
Rather than do this for every single control, is there a way I could do this in some kind of For Each Loop? I am fairly new to ASP.Net (VB) so I am still learning. Thanks
Technically you could do this with a loop, something pseudocoded like this.
foreach(Control currentControl in this.Controls)
{
var currentTextbox = currentControl as TextBox;
if(currentTextbox != null && currentTextbox.Id.EndsWith("_Date"))
//DO your stuff here
}
But honestly I'm not sure that is going to get you much, especially if there are lots of other controls...As this has to attempt to cast the item to the target type first. WHich if you have a lot of failures, could be a big performance hit.

ASP.NET EnqityDataSource WhereParameters, creates new property

I am trying to populate GridView, using EntityDataSource(code behind), I need to able to sort GridView. However when I sort i get error:
A property with name 'aspnet_Users.UserId1' does not exist in metadata for entity type
So I beleive it is because I generate where parameter in code behind:
ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName"));
Full code is :
ActiveEnqDataSource.ConnectionString = db.Connection.ConnectionString;
ActiveEnqDataSource.DefaultContainerName = "Entities";
ActiveEnqDataSource.EntitySetName = "Enquiries";
ActiveEnqDataSource.Include = "UserCars.CarModel.CarMake, Category, aspnet_Users";
ActiveEnqDataSource.EnableUpdate = true;
ActiveEnqDataSource.EnableInsert = true;
ActiveEnqDataSource.EnableDelete = true;
ActiveEnqDataSource.AutoGenerateWhereClause = true;
ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName"));
Any suggestions? Thank you very much! The gridview itself renders perfectly, only thing I cannot sort it, any "whereParameters" I add, Add 1 to the property e.g UserId1,EnquiryStatus1, ProdauctName1. etc...
I got a similar error because I was adding the where clause each time the page was posted back. Dropping my code that generated the where clause inside an IsPostback statement fixed the problem:
if (!IsPostBack) {
// code to add where parameters
}
I got the same error when I used markup to define a Where parameter AND then I added the same parameter in code. Somewhere along the line, the 1 at the end of the parameter name was added.

I want to add items to an ASP.Net combobox using Javascript

I want to add an item to an ASP.Net combobox using Javascript. I can retrieve the ID (No Masterpage). How can I add values to the combobox from Javascript? My present code looks like this.
//Fill the years (counting 100 from the first)
function fillvarYear() {
var dt = $('#txtBDate').val();
dt = dt.toString().substring(6);
var ye = parseInt(dt);
//Loop and add the next 100 years from the birth year to the combo
for (var j = 1; j <= 100; j++) {
ye += 1; //Add one year to the year count
var opt = document.createElement("OPTION");
opt.text = ye;
opt.value = ye;
document.form1.ddlYear.add(opt);
}
}
To see the value on postback:
string selectedValue = Request.Params[combobox.UniqueId]
Remember, changing the values in a combobox with javascript will cause an Event Validation exception to be thrown, and is generally a bad idea, as you'll have to explicitly disabled event validation.
I'd recommend placing the combobox in an update panel, so you can read txtBirthDate on the server and generate the appropriate data. You then won't have to manually preserve state either.
Always remember, ASP.NET controls are nothing "fancy" - they always end up at some point becoming standard HTML elements.
Try checking out this site. It has a pretty nice demo and overview. Take note however that you are altering the data at the client side - this means you will need to do it on each and every request because the ViewState will not be updated.
TBH, you are probably better off just using a HTML control rather than ASP ComboBox..
Can I ask why you are changing items via Javascript? (out of curiosity) :)
I found a possible solution. I don't know why the earlier code didn't work for me, but the line below
document.form1.ddlYear.appendChild(new Option(ye, ye));

Resources