I've a DropDownList - ASP.NET WebForm where it's filled up with roles and did it like the below from database:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LoadDropDownBox();
}
}
public void LoadDropDownBox()
{
ddlUserRole.DataSource = aDbOperations.GetRoles(); //List of objects here
ddlUserRole.DataTextField = "roleName";
ddlUserRole.DataValueField = "roleId";
ddlUserRole.DataBind();
}
It works fine. Now my requirement is to get the selected role of a user when I edit or update user details. So say a user has role Admin, then while editing, the admin role should be selected by default along with other values in the DropDownList. So I tried something like this in the same default page:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
foreach (var item in aDbOperations.GetUserWithId(id)) //Passing query string here to match the id of the editing details
{
ddlUserRole.Value = item.roleName; //Get the selected role name by default while editing user details
}
LoadDropDownBox();
}
}
Even tried this:
ddlUserRole.SelectedItem.Value = item.roleName;
Though it didn't work and not getting the value selected by default along with other role values from database. Anything missed here?
Update - 1: Even tried the below one, but still not done
if (ddlUserRole.Items.FindByText(item.roleName.ToString()) != null)
{
ddlUserRole.Items.FindByText(item.roleName.ToString()).Selected = true;
}
Move your foreach after the LoadDropDownBox() function because the drop down has no loaded values before then.
Then if you know your dropdown contains the value FOR SURE then you can just do
ddlUserRole.SelectedValue = item.roleId.ToString();
Otherwise you would need to do a check to prevent an error like so:
ListItem selectedListItem = ddlUserRole.Items.FindByValue(item.roleId.ToString());
if (selectedListItem != null)
{
selectedListItem.Selected = true;
}
Your final code should look like this:
if(!IsPostBack)
{
LoadDropDownBox();
foreach (var item in aDbOperations.GetUserWithId(id)) //Passing query string here to match the id of the editing details
{
ListItem selectedListItem = ddlUserRole.Items.FindByValue(item.roleId.ToString());
if (selectedListItem != null)
{
selectedListItem.Selected = true;
}
}
}
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);
}
I need to add a search box to a listbox that has data pulling from SQL - I'm not sure how as it isn't my code. I just need to add the search function. The listbox holds user names and surnames. So all I have to work with is lbUsers (the listbox name).
Thus far I have it to search a user name but it's only displaying the closest search - I want the code to filter out everything containing what I have typed into the search box:
private void btnSearch_Click(object sender, EventArgs e)
{
this.lbUsers.SelectedItems.Clear();
for (int s = this.lbUsers.Items.Count - 1; s >= 0; s--)
{
if (this.lbUsers.Items[s].ToString().ToLower().Contains(this.tbSearch.Text.ToLower()))
{
this.lbUsers.SetSelected(s, true);
}
}
}
I also don't want all the users to display - only those relating to the search box's criteria.
You will have to do this manually:
Save all users in a list
Filter the list accoring the text in the TextBox
Add the results to the ListBox
This is a minimal example:
List<User> users = new List<User>();
private void txtFilter_TextChanged(object sender, EventArgs e)
{
List<User> displayList = this.users;
if(this.txtFilter.Text != string.Empty)
{
displayList = this.users.Select(u => u.Name == this.txtFilter.Text);
}
this.lbUsers.Items.Clear();
this.lbUsers.Items.AddRange(displayList);
}
I think the best way to do this is through visibility. This way you don't have to keep creating/disposing of listbox items.
For example, the code below would do what you want:
foreach (var item in lbUsers.Items)
{
if (item.ToString().Contains(this.tbSearch.Text))
{
item.Visible = true;
}
else
{
item.Visible = false;
}
}
I am displaying columns in a GridView and one of the columns is a dropdownlist. I want to be able to save the option selected in the dropdownlist as soon as something is selected. I have done this with one of the columns that has a textbox so I was hoping to do something similar with the DropDownList.
The code for the textbox and dropdownlist:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
How to I create an update function for a dropdownlist?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
Dropdownlist:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
I created an OnSelectedIndexChanged function to get the selected value. But how do I then save that value? Is there a way to pass it into the UpdateSerialReason function?
Just move the string sel declaration outside the scope of DDLReasons_SelectedIndexChanged and get the Text of the SelectedItem since it's included in your data source.
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
The way you had it previously it was only available in the local scope, i.e, inside the method in which it was being declared and used.
You can get selected value when you call your function:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
You will lose your value after postback is done if you save value to variable as Equalsk suggested. If you need to use your value on the other page you can save it in session.
If you are working within one asp.net page you can do as I suggested above. Then you can skip the postback on your DropDownList and call UpdateSerialReason when you need :)
And you might want to add property ViewStateMode="Enabled" and EnableViewState="true"
I have a gridcontrol which is binded to a list using a BindingSource.
invoice_GroupListBindingSource.Datasource= _list.
GridControl.DataSource = invoice_GroupListBindingSource
Now there is one checkedit column (let's call it Invoice_Bool). The functionality requirement is when user select anyone of he column all the datarows should be updated and select column for them should also be selected.
Foloowing is the code I tried:
private void invoice_GroupListBindingSource_CurrentItemChanged(object sender, EventArgs e)
{
Data.InvoiceGroupList.InvoiceGroupInfo current;
if (invoice_GroupListBindingSource.Current == null)
{
current = null;
}
else
{
current = ((Data.InvoiceGroupList.InvoiceGroupInfo)invoice_GroupListBindingSource.Current);
}
if (current.Invoice_Bool)
{
foreach (var item in _invoice_list)
{
item.Invoice_Bool = true;
}
this.invoice_GroupListBindingSource.DataSource = _invoice_list;
}
}
With this I am getting an updated list with all the Invoice_Bool true when user selects any of them (as required), however in the front-end(in the grid) all the bool values are still unselected. Any idea how to update the grid also when data source changes.. ideally it should be done automatically but I am not sure why it is not updating.
I have a table called me : with 3 columns: Name,SecName,Code
void GridView1_RowEditing(Object sender, GridViewEditEventArgs e)
{
name = "";
subname = "";
code = "";
}
How can I get the name,subname,code from selected row into those variables.
Thanks
I think you should be able to get the currently bound item by doing:
((ObjectBoundToGridRow)e.Item.DataItem).<X>
So you can extract it from the source object, but you can also do:
string name = DataBinder.GetPropertyValue(e.Item.DataItem, "Name");
HTH.