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;
Related
I have an Album table with an Id_album attribute. and a songs table with Id_song attribute and Id_album as foreign key attribute. In the aspx page I have a drop down list of the album names to be selected to get its Id and use that Id in the songs table to add new songs ofthat album *depending on Id)
what I have done so far returns for me Id_album 1 whenever an album name is selected from the drop down list. In other words, the songs are all added to album of Id=1.what is going wrong??
this is the aspx page:
public partial class newSongs : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MusicStoreBL bl = new MusicStoreBL();
var data = bl.GetAlbums();
//GetAlbums is a function that returns the Id_album, AlbumName
albums.DataSource = data;
//albums is the HTML dropdownlist
albums.DataTextField = "AlbumName";
albums.DataValueField = "Id_Album";
albums.DataBind();
}
protected void save_Click(object sender, EventArgs e)
{
Song song = new Song();
//Song is a get/set model
song.Id_album = int.Parse(albums.SelectedValue);
song.SongName = songName.Text;
song.SongAuthor = author.Text;
song.MusicArtist = songArtist.Text;
song.Genre = genre.Text;
MusicStoreBL bl = new MusicStoreBL();
bl.CreateNewSong(song);
Response.Redirect("albumSelection.aspx");
}
}
You should place your data binding code in the Page Load event handler inside the following if statement:
if(!Page.IsPostBack)
{
MusicStoreBL bl = new MusicStoreBL();
var data = bl.GetAlbums();
//GetAlbums is a function that returns the Id_album, AlbumName
albums.DataSource = data;
//albums is the HTML dropdownlist
albums.DataTextField = "AlbumName";
albums.DataValueField = "Id_Album";
albums.DataBind();
}
This way you fetch your data only once and then you bind them to the corresponding drop down list control. Otherwise, each time you trigger a postback, like selecting an element from your drop down list control or clicking on a button and so on, your data bind code in the Page_Load runs from the start.
So why you get all the time the Id=1?
The reason why you get every time as an Id the 1 is the fact that every time you click the save the code in the Page_Load runs. The data bind happens and the first item of the drop down list is the selected one.
I have developed a website in ASP.NET that can add articles into a another table that shows a product.
I have a table that displays items in a warehouse and a table showing the materials required to produce a certain product. Using a drop down list you can see which products are manufactured. When the user wants to add to the article, he pushes a button. But after the page loaded on my dropdown list shows the lowest value again instead of keeping its value. Visit the site, change the product (produkt in swedish) from "Cykel" (bicycle) to "car" and add any article and you will understand the problem. Can I do something with page load to find a solution?
Maybe I should mention that I use a datasource that I'm binding the dropdown with.
If you are binding your dropdown in pageload bind it in !ispostback..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Bind your dropdown
}
}
in onChange of drop down call a function, Assume that is storeValue() function and do somthing like this, [you can add attribute to dropdown as onchange="storeValue(this.value);"]
function storeValue(val)
{
localStorage.setItem("dropdownvalue",val);
}
and
var val="";
$(document).ready(function(){
val=localStorage.getItem("dropdownvalue");
//assign your value to dropdown list from here...
});
With help from the gentlemen above I find out to solve the problem. I used function that is called every time the dropdownlist index is changed. The function save the index in a session.
if (!Page.IsPostBack)
{
try
{
string test = (string)Session["test"];
int value = int.Parse(test);
DropDownList2.SelectedIndex = value;
}
catch
{
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Session["test"] = ""+ DropDownList2.SelectedIndex;
}
I am having trouble getting my datasource linked to my repeater through this code
protected void Page_Load(object sender, EventArgs e)
{
//HiddenField used as a placholder
HiddenField username = list.FindControl("username") as HiddenField;
//list is a DataList containing all of the user names
list.DataSource = Membership.GetAllUsers();
list.DataBind();
//Creates a string for each user name that is bound to the datalist
String user = username.Value;
//profilelist is a repeater containing all of the profile information
//Gets the profile of every member that is bound to the DataList
//Repeater is used to display tables of profile information for every user on
// the site in a single webform
profilelist.DataSource = Profile.GetProfile(user);
profilelist.DataBind();
}
I am getting the error message
An invalid data source is being used for profilelist. A valid data source must implement either IListSource or IEnumerable.
Well the reason why it will not work is because Profile.GetProfile returns ProfileCommon. As the error states the type you set profilelist.Datasource equal to, must be IListSource or IEnumerable.
I would suggest not using a repeater since you don't have actual repeating data to display.
EDIT
I think this is what you want to do.
IEnumerable<ProfileCommon> myProfileList = new IEnumerable<ProfileCommon>();
foreach(var user in userlist)
{
myProfileList.Add(Profile.GetProfile(user));
}
profilelist.datasource = myProfileList;
Your going about this wrong. As Etch said, a repeater is for lists of things. GetProfile doesn't return a list.
You're better off just putting your controls in a panel and assigning them in the "list" controls ondatabinding event.
In other words, you don't need a repeater here.
I forgot to post this up but for anyone that needs to do something similar here is the code behind that works
protected void Page_Load(object sender, EventArgs e)
{
List<MembershipUserCollection> usernamelist = new List<MembershipUserCollection>();
usernamelist.Add(Membership.GetAllUsers());
List<ProfileCommon> myProfileList = new List<ProfileCommon>();
foreach (MembershipUser user in usernamelist[0])
{
string username = user.ToString();
myProfileList.Add(Profile.GetProfile(username));
Label emailLabel = profilelist.FindControl("EmailLabel") as Label;
}
}
At the moment this is displaying about 15 user names and providing an ability to link to each of theses users respective profiles.
I am writing a web site in Visual Studio, something like an on-line library. I have a GridView on the first page that presents all of the books available from the data source and some other properties also contained in the data source. The GridView contains check boxes and the user can choose which books he wants to order by checking a box. My question is how can I use the data in the selected rows, the list of books with their properties and show that list on another page, so that the user is able to know which items he has selected?
I tried with a for loop on the FirstPage:
protected void Page_Load(object sender, EventArgs e)
{
List<int> ids = new List<int>();
if (!IsPostBack)
{
}
else
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
int bookID = (int)GridView1.DataKeys[i][0];
CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox");
if (cb.Checked)
{
ids.Add(bookID);
}
}
Session["Ids"] = ids;
Response.Redirect("SecondPage.aspx");
}
}
and on the SecondPage:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtBooks = new DataTable("Books");
dtBooks.Columns.Add(new DataColumn("ID", typeof(int)));
if (!IsPostBack)
{
var list = (List<int>)Session["Ids"];
foreach (int id in list)
{
if (Request.QueryString["bookID" + id] != null)
{
DataRow row;
row = dtBooks.NewRow();
row["ID"] = Request.QueryString["bookID" + id];
dtBooks.Rows.Add(row);
}
}
GridView1.DataSource = dtBooks;
GridView1.DataBind();
}
else
{
}
}
but I get no GridView table on the second page. I would be very grateful if anyone notices my mistake and points it out. Hope you can help me.
This is a common issue when setting session variables before a redirect. I think you can work around it by using the overloaded Response.Redirect method:
Response.Redirect("...", false); // false = don't stop execution
See here for more details:
Session variables lost after Response.Redirect
Another option is to store the IDs in a hidden field, and access them with Page.PreviousPage, like this:
HiddenField hidden = (HiddenField)Page.PreviousPage.FindControl("MyHiddenField");
string values = hidden.Value;
Lastly, depending on what the page is doing, you might want to use Server.Transfer here. There are drawbacks to this approach, but there are situations where it's applicable.
In your second page, you are checking for a query string variable before adding a row to dtBooks:
if (Request.QueryString["bookID" + id] != null)
However, you are not passing any query strings when you redirect:
Response.Redirect("SecondPage.aspx");
At a guess, I would think that you originally tried using the query string to pass the IDs, before changing to the session and you haven't updated all of your code.
I am somewhat concerned about your first page code, though. You do realize that you will redirect to the second page whenever a post back occurs? That means that no matter what buttons / controls you have on the first page, if they post back for any reason, you will redirect to the second page.
EDIT AFTER COMMENTS
If you aren't using the query string, then don't use the query string:
foreach (int id in list)
{
DataRow row;
row = dtBooks.NewRow();
row["ID"] = id;
dtBooks.Rows.Add(row);
}
I have a Program Class, with properties as Id, ProgramName,ShortName and Code, im my app
I have a ASP DDL like
<asp:DropDownList ID="DDLProgram" runat="server"
OnSelectedIndexChanged ="OnDDLProgramChanged" AutoPostBack = "true">
</asp:DropDownList>
My OnDDLProgramChanged method is defined as
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
List<CcProgramEntity> programEntities = GetAllPrograms();
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
//My Problem goes here
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
My list is getting all the records correctly, I have checked it. But whenever I am changing an item in the DDL, the selected index in not changing. The selected index is remaining zero.Therefore, I am not being able to get the code of other items but the 0 index's item.
Can anyone help me in this case?
You are binding the data again in your selectedIndex Change event and it will reset your current SelectedIndex after rebinding. You don't need to rebind the data to your dropdown in SelectedIndex Change Event
It should be like..
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
You have to bind data to the DropDownList on page load method
if (!IsPostBack)
{
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
DDLProgram.DataBind();
}
Otherwise it will bind data everytime and hence clear the selection
Why are you assigning the DataSource in OnDDLProgramChanged, this would be resetting the selection you make.