Error When Databinding to Control - c#

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.

Related

How to populate the form fields for updation purpose based on the dropdown list selected item in entity framework?

I'm working on Content Management System in ASP .Net and I have been working on the updating operation using an EF code first approach, but I'm not able to populate the form fields based on the selected item from the dropdown list.
I tried to populate the form field, but I'm not able to do so, I tried the methods like .Find() but it is not working
protected void ddlSelectCourse_SelectedIndexChanged(object sender, EventArgs e)
{
CourseInfo ci = new CourseInfo();
var selectedId = ci.Id;
var obj = irep.GetSingleCourse(selectedId);
txtCourseName.Text = obj.CourseName;
}
I want to populate txtCourseName.Text field to be populated by the Course name
Should you not use the index from the EventArgs in the change event? From what I can see you are using selectedId from a freshly "newed" up CourseInfo object, presumably id is an int, in which case it will be 0

Save the dropdowns value when reloading the page?

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;
}

Add dynamic ASP.NET controls via a DropDownList to the page

- Primary Info:
In my recent project, I need to have a page with a DropDownList with some items like 'firstName' , 'lastName' , 'Age' and etc. I want to add optional controls to the page when every item selected by user. For example when user select the 'Age' another dropdownlist created dynamically with these values : 'Less than 10'
'Between 10 and 30'
'more than 30'
Here is a button that add this user selection to listBox and let user to choice another options. (I made a query at last according to user choices and send it to db)
- What I do:
I create a dropDownList and set it's AutoPostBack property to true and adds some items in it and user must select one of those item. then I add user SelectedValue of dropDownList in a Cache variable before page post back happens:
protected void DropDownListColumnNameSelectedIndexChanged(object sender, EventArgs e)
{
Cache["SelectedKey"] = dropDownListColumnName.SelectedValue;
}
When user select an item from dropDownList *DropDownList_SelectedIndexChanged* fire, and I must create controls dynamically in a place holder:
var textBoxName = new TextBox
{
ID = "textBoxName",
CssClass = "str-search-textbox-highlight",
ViewStateMode = ViewStateMode.Disabled
};
placeHolderFirstItem.Controls.Add(textBoxName);
- What is the problem?
When I try add new control in current Button_Click event, control added successfully to page but I can't find it by placeHolderFirstItem.Controls.Find("textBoxName") actually placeHolderFirstItem.Controls.Count is always zero. So I can't get textBoxName.Text values.
I try to google that for any solution and I found some solution that I must add controls in Page.OnInit so I add controls in overridden OnInit(e):
protected override void OnInit(EventArgs e)
{
if (!Page.IsPostBack) return;
var textBoxName = new TextBox
{
ID = "textBoxName",
CssClass = "str-search-textbox-highlight",
ViewStateMode = ViewStateMode.Disabled
};
placeHolderFirstItem.Controls.Add(textBoxName);
}
after doing this I can find "textBoxName" in placeHolderFirstItem, but it fire before DropDownList_SelectedIndexChanged !
so how can I add new controls to place holder exactly when user change the dropDownList value and how can I read new controls value?
Thanks in advance,
Mohsen.
- Updated:
Here is the better solution
(http://forums.asp.net/p/1959726/5596531.aspx?p=True&t=635244790943067485&pagenum=1)
When you are dynamically adding controls, you have to reload the controls into the control tree everytime thereafter for it to appear. With the help of viewstate, you could change your code sample to have:
ViewState("ShowTextbox") = true
And then in your init routine:
protected override void OnInit(EventArgs e)
{
if (!Page.IsPostBack) return;
if (ViewState("ShowTextBox") == true) {
var textBoxName = new TextBox
{
ID = "textBoxName",
CssClass = "str-search-textbox-highlight",
ViewStateMode = ViewStateMode.Disabled
};
placeHolderFirstItem.Controls.Add(textBoxName);
}
}
Please note it's much easier to have a control on the control tree, and then show/hide by setting Visible to true/false, because of these ASP.NET control tree issues.

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;

ASP.NET GridView user control problem

I have a user control that contains a GridView. I pass an IEnumerable data source object to the user control instance. How can I use a ForEach to loop through the data source in the user control code behind to display the columns I want from the data source?
So far, I have the following code in the code behind of the user control:
public IEnumerable<object> DataSource { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
this.GridView1.DataSource = DataSource;
foreach (var item in DataSource)
{
//The line below gives an error - what's the correct way to do this?
this.GridView1.Columns.Add(new BoundColumn() {DataField = "What to put here", HeaderText = "What to put here"; }
}
this.GridView1.DataBind();
}
You should not loop on all items of the DataSource, you are looping vertically on all records while you want to loop only once, horizontally, on all columns. Since you know the list of properties of the object contained in the DataSource you can do this statically and not even in a foreach. If you really want to have it dynamic then you could use Reflection and loop on all public fields of the first object available in your IEnumerable.
Edit: to find all public fields of an object via reflection see here:
How can I find all the public fields of an object in C#?
but this only applies if you want to make it generic, if you already know that your object contains some fields like Name, Address and Email, for example, you do not need it.

Categories

Resources