Update dropdown after Items.Clear() - asp.net

I populate a dropdown with several items. When the user chooses one of these items, a second dropdown gets populated.
When the user clicks on the "x" button on the first dropdown, the two dropdown must be cleared. The first dropdown gets cleared automatically, and i clear the second dropdown by using "dropdown.Items.Clear()".
It happens that when i load again the data for the first dropdown, the second dropdown does not update.
This is the code:
protected void DropDownDiagStati_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedIndex = this.DropDownDiagStati.SelectedIndex;
PopulateDDLStates(selectedIndex);
}
private void PopulateDDLStates(int selectedIndex)
{
// Ottengo i diagrammi di stato in sessione
ArrayList diagrammiStato = Session["stateDiagrams"] as ArrayList;
if(selectedIndex > 0)
{
// Ottengo il diagramma di stato selezionato
DocsPaWR.DiagrammaStato currDiagStato = (DocsPaWR.DiagrammaStato)diagrammiStato[selectedIndex - 1];
// Ottengo gli stati del diagramma di stato selezionato
Stato[] stati = currDiagStato.STATI;
for(int i = 0; i < stati.Length; i++)
{
ListItem item = new ListItem();
item.Value = Convert.ToString(stati[i].SYSTEM_ID);
item.Text = stati[i].DESCRIZIONE;
this.DropDownStati.Items.Add(item);
this.UpPanelStatiDdl.Update();
}
}
else
{
this.DropDownStati.Items.Clear();
this.UpPanelStatiDdl.Update();
}
}
I see only the old value in the second dropdown and i cannot select it.

You need to remove update pane or you can set data source to drop-down.
ddl1.datasource = DataSource;
ddl1.DataTextField = "name";
ddl1.DataValueField = "id";
ddl1.DataBind();

The problem was that the clear function removes also the default empty Item. I solved by creating a private method that removes all the items but the first one.

Related

How to create items programmatically in Sitecore

In the content tree, the structure is as follows
Home
-England
-France
-Germany
There is a sublayout (CommentsForm.ascx), which is used in all the 3 pages. When user browses 'France' and submits a comment, the 'Comment' item should get saved under 'France' and so on..
In this scenario, the Parent item (under which the new item has to be created), is dynamic. So, how to get the parent item in such case. Is this correct?
protected void btnSubmit_Click(object sender, EventArgs e)
{
Sitecore.Data.Database masterDB = Sitecore.Configuration.Factory.GetDatabase("master");
Item parentItem = Sitecore.Context.Item;
string name = "Comment_" + Sitecore.DateUtil.IsoNow;
TemplateItem template = masterDb.GetTemplate("/sitecore/templates/userdefined/Comment");
using (new SecurityDisabler())
{
//how to go about here??
//newItem["Author"] = txtAuthor.text;
//newItem["CommentText"] = txtComments.Text;
//parentItem.Add("name", template);
}
}
You can use UserSwitcher safer in production, but you can also use SecurityDisabler using(newSecurityDisabler()){}
Editing and renaming must happen in an Editing.BeginEdit() transaction
Sitecore.Data.Database masterDB = Sitecore.Configuration.Factory.GetDatabase("master");
Item parentItem = Sitecore.Context.Item;
string name = "Comment_" + Sitecore.DateUtil.IsoNow;
var template = masterDb.GetTemplate("/sitecore/templates/userdefined/Comment");
using (new Sitecore.SecurityModel.SecurityDisabler())
{
try
{
Item newItem = parentItem.Add("Name", template);
if (newItem!=null)
{
newItem.Editing.BeginEdit();
newItem["Author"] = txtAuthor.text;
newItem["CommentText"] = txtComments.Text;
newItem.Editing.EndEdit();
}
}
catch
{
newItem.Editing.CancelEdit();
}
}
Create items programmatically based on template in sitecore using the simple code
// The SecurityDisabler is required which will overrides the current security model, allowing the code
// to access the item without any security.
using (new Sitecore.SecurityModel.SecurityDisabler())
{
// Get the master database
Sitecore.Data.Database master = Sitecore.Data.Database.GetDatabase("master");
// Get the template for which you need to create item
Items.TemplateItem template = master.GetItem("/sitecore/templates/Sample/Sample Item");
// Get the place in the site tree where the new item must be inserted
Item parentItem = master.GetItem("/sitecore/content/home");
// Add the item to the site tree
Item newItem = parentItem.Add("NameOfNewItem", template);
// Set the new item in editing mode
// Fields can only be updated when in editing mode
// (It's like the begin transaction on a database)
newItem.Editing.BeginEdit();
try
{
// Assign values to the fields of the new item
newItem.Fields["Title"].Value = "NewValue1";
newItem.Fields["Text"].Value = "NewValue2";
// End editing will write the new values back to the Sitecore
// database (It's like commit transaction of a database)
newItem.Editing.EndEdit();
}
catch (System.Exception ex)
{
// Log the message on any failure to sitecore log
Sitecore.Diagnostics.Log.Error("Could not update item " + newItem.Paths.FullPath + ": " + ex.Message, this);
// Cancel the edit (not really needed, as Sitecore automatically aborts
// the transaction on exceptions, but it wont hurt your code)
newItem.Editing.CancelEdit();
}
}
using (new Sitecore.SecurityModel.SecurityDisabler())
{
Item newItem = parentItem.Add("Name", TemplateItem.TemplateId);
newItem.Editing.BeginEdit();
newItem.Fields[Constants.IDs.Fields.SicParent.Code].Value = row.SicCode.ToString();
newItem.Fields[Constants.IDs.Fields.SicParent.Description].Value = row.Description;
// this field is a DropList
newItem.Fields[Constants.IDs.Fields.SicParent.Grouping].SetValue(groupItem, true);
newItem.Editing.EndEdit();
}
You can add and item to parentItem and then edit the new item like this:
using (new SecurityDisabler())
{
Item newItem = parentItem.Add("name", template);
newItem.Editing.BeginEdit();
newItem["Author"] = txtAuthor.text;
newItem["CommentText"] = txtComments.Text;
newItem.Editing.EndEdit();
}

Show selected item in JComboBox to JTextField

Good day every one, i need a little bit of help here. I was able to connect my database and show those item to a JComboBox, my straggle as of the moment is that every time i change the item on my JComboBox the item that will show on my JTextField is always the first item in my JComboBox even if i click the second or third item show in my JComboBox
public void JComboBoxToJTextFlied()
{
String dataSource = "CheckWriterDB";
String dbURL = "jdbc:odbc:" _ dataSource;
String temp = (String)listOfSuppliers.getSelectedItem();
String sql = (select Suppliers from SuppliersTable where Suppliers=?)
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect= DriverManager.getConnection(dbURL, "", "");
PrepareStatement pst = connect.prepareStatement(sql);
pst.setString(1, temp);
resultSet result = pst.executeQuery();
//My Action perform so that everytime i change the item in my JComboBox
the new item will be shown in my JTextField
listOfSuppliersCombo.addItemListener(new ItemListener()
public void itemStateChange(ItemEvent event)
{
If(event.getStateChange() == ItemEvent.SELECTED)
{
try
{
if(result.next())
{
String add = result.getString("Suppliers")
newSuppliersEntryField.setText(add);
}
}
catch()
{
system.out.println("Your error is: " + e)
}
}
}
);
}
catch(Exception e)
{
System.out.println("Your error is: " + e)
}
}
note: listOfSupplierCombo is my JComboBox and newSuppliersEntryField is my JTextField.
How do i improve my codes so that every time i change the item in my JcomboBox it will show the same item in my JTextField? Because everytime i change the ITem in JcomboBox the item that will appear in my JText field is always the first item in my comboBox even if i chose the second, third, fourth and so on in my Jcombobox. Thank you so much.
Try it:
If(event.getStateChange() == ItemEvent.SELECTED)
{
event.getSource();
// It returns the selected item
//you also can check it by:
System.out.println(event.getSource());
}

CheckBoxList '.Selected' is returning false in every situation

I am trying to grab multiple values from a checkboxlist and add them to a list, But checked values are always false even though the list contains appropriate count value.
code to populate:
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
HelpingOthersEntities helpData = new HelpingOthersEntities();
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>();
locCkBox.DataSource = theDataSet;
locCkBox.DataTextField = "slAddress";
locCkBox.DataValueField = "storeLocationID";
locCkBox.DataBind();
code for adding to list:
List<int> locList = new List<int>();
for (int x = 0; x < locCkBox.Items.Count; x++){
if(locCkBox.Items[x].Selected){
locList.Add(int.Parse(locCkBox.Items[x].Value));
}
}
The problem I am having is that I cannot get into items.selected
my value is always false.
I have tried populating the checkboxes from postback but i get the same result. My list gives me the appropriate .Count amount of values, but items.selected = false?
I have tried a foreach loop to add to list as well but I get the same results over and over. Am i missing an event or something?
I'm going to take a guess here and say that your code that does the population stuff is being called in the pageload event, so you have something like the following.
private void Page_Load()
{
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
HelpingOthersEntities helpData = new HelpingOthersEntities();
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>();
locCkBox.DataSource = theDataSet;
locCkBox.DataTextField = "slAddress";
locCkBox.DataValueField = "storeLocationID";
locCkBox.DataBind();
}
If that's the case then your effectively writing over the postback data on each request. To sort this out you need to only perform the databinding when its not a postback, so you need to change the above code to
private void Page_Load()
{
if (!IsPostBack)
{
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
HelpingOthersEntities helpData = new HelpingOthersEntities();
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>();
locCkBox.DataSource = theDataSet;
locCkBox.DataTextField = "slAddress";
locCkBox.DataValueField = "storeLocationID";
locCkBox.DataBind();
}
}
You should then be able to test the Selected property of the items. I'd also probably change the code your using to test for the selected to something like
List<int> locList = new List<int>();
foreach(var item in locCkBox.Items)
{
if(item.Selected)
{
locList.Add(int.Parse(item.Value));
}
}
or if your on a .NET version with LINQ available
List<int> locList = new List<int>();
(from item in locCkBox.Items where item.Selected == true select item).ForEach(i => locList.Add(i.Value));
Make sure while binding the checkboxlist in page load you have set this check.
if (!Page.IsPostBack)
{
...bind your data
}
This should do the trick.

How can I populate a drop down box with all the possible SeriesChartType options?

I wish to populate a drop down box with each possible SeriesChartType so that my users may choose an appropriate chart type.
How can I iterate through the SeriesChartType collection (it's in the namespace System.Web.Ui.DataVisualization.Charting) and return each possible option so I can add it to the drop down box?
Thanks.
This worked for me in VB - I had to instantiate a new instance of the SeriesChartType which allowed me to use the [Enum].GetNames Method.
I was then able to add them to the drop down box as shown:
Dim z As New SeriesChartType
For Each charttype As String In [Enum].GetNames(z.GetType)
Dim itm As New ListItem
itm.Text = charttype
ddl_ChartType.Items.Add(itm)
Next
Thanks to everyone for your answers. mrK has a great C alternative to this VB code.
foreach (ChartType in Enum.GetValues(typeof(System.Web.UI.DataVisualization.Charting))
{
//Add an option the the dropdown menu
// Convert.ToString(ChartType) <- Text of Item
// Convert.ToInt32(ChartType) <- Value of Item
}
If this isn't what you're looking for, let me know.
You could bind data in the DataBind event handler:
public override void DataBind()
{
ddlChartType.DataSource =
Enum.GetValues(typeof(SeriesChartType))
.Cast<SeriesChartType>()
.Select(i => new ListItem(i.ToString(), i.ToString()));
ddlChartType.DataBind();
}
and then retrieve the selected value in the SelectedIndexChanged event handler like this:
protected void ddlChartType_SelectedIndexChanged(object sender, EventArgs e)
{
// holds the selected value
SeriesChartType selectedValue =
(SeriesChartType)Enum.Parse(typeof(SeriesChartType),
((DropDownList)sender).SelectedValue);
}
Here's a generic function:
// ---- EnumToListBox ------------------------------------
//
// Fills List controls (ListBox, DropDownList) with the text
// and value of enums
//
// Usage: EnumToListBox(typeof(MyEnum), ListBox1);
static public void EnumToListBox(Type EnumType, ListControl TheListBox)
{
Array Values = System.Enum.GetValues(EnumType);
foreach (int Value in Values)
{
string Display = Enum.GetName(EnumType, Value);
ListItem Item = new ListItem(Display, Value.ToString());
TheListBox.Items.Add(Item);
}
}

Return ASP DDL or Telerik control

I'm trying to write a more generic method that will populate either an ASP.NET dropdownlist OR a telerik RadComboBox with states. I'd like to pass the control in as a parameter to the method. I have a DataTable that holds all the states, which I loop through (see below) - I'd like to make this applicable to a Telerik RadComboBox - so I need to change the first parameter, and also the part where I Insert a new ListItem - for Telerik RadComboBox it is new RadComboBoxItem. How can I do this?
public void PopulateStates(DropDownList ddlStates, string country)
{
ddlStates.Items.Clear();
DataLookup dl = new DataLookup();
DataTable dt = dl.GetStatesByCountry(country);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
ddlStates.Items.Insert(0, new ListItem(""));
for (int i = 0; i < dt.Rows.Count; i++)
{
ddlStates.Items.Add(new ListItem(dt.Rows[i]["STCD_Descr"].ToString(),
dt.Rows[i]["STCD_State_CD"].ToString()));
}
}
}
}
I looked up the telerik documentation & there doesn't seem to be common way of doing - what you are trying to do.
If it is possible, try using the databinding (setting the DataSource & calling DataBind).
Note: I haven't tried it. But I think that should be supported by both.
Since ListBox and RadComboBox does not have common classes except for the "Control" class you will need to check the actual type.
How about the following code?
public void PopulateStates(Control ddl, string country)
{
object listItem = new object();
switch (ddl.GetType().Name)
{
case "RadComboBox":
listItem = listItem as RadComboBoxItem;
ddl = ddl as RadComboBox;
break;
case "ListBox":
listItem = listItem as ListItem;
ddl = ddl as ListBox;
break;
default:
return;
}
// proceed with your code
}

Resources