RadComboBoxItems not being added to multiple RadComboBoxes - asp.net

All I'm really trying to do is populate three different comboboxes with the same item. When this code executes below only one combobox is getting the values. Any help is welcomed. Thanks!
for (int i = 0; i < 100; i++)
{
RadComboBoxItem li = new RadComboBoxItem();
li.Text = i.ToString();
li.Value = i.ToString();
InputPairThousandValueComboBox.Items.Add(li);
InputUsertThousdandValueComboBox.Items.Add(li);
InputCurrentlyListedThousdandComboBox.Items.Add(li);
}

I couldn't find anything in the Telerik docs that says this explicitly, but it appears a single instance of a RadComboBoxItem can only be contained in a single RadComboBox; you can't share a RadComboBoxItem between controls.
The docs do hint to this: the RadComboBoxItem has an 'owner' property that is a reference to the RadComboBox that contains the item (implying that there can be only 1 owner)
Under the covers, the second & third Add(...) calls most likely first remove the item from the combo box its already in.
So, you'll have to create a separate RadComboBoxItem for each RadComboBox. Here's one way you could do it using the RadComboBoxItem constructor that takes the text and value as arguments.
for (int i = 0; i < 100; i++)
{
var val = i.ToString();
InputPairThousandValueComboBox.Items.Add(new RadComboBoxItem(val, val));
InputUsertThousdandValueComboBox.Items.Add(new RadComboBoxItem(val, val));
InputCurrentlyListedThousdandComboBox.Items.Add(new RadComboBoxItem(val, val));
}

For those still running into this issue, a way I found is adding the items as a dictionary, then binding with a datasource.
link to telerik form
Dictionary<string, string> comboSource = new Dictionary<string, string>();
comboSource.Add("", "");
comboSource.Add(user.Rs.GetString("txtDate"), "phDate");
comboSource.Add(user.Rs.GetString("txtBranch"), "mhBranch");
comboSource.Add(user.Rs.GetString("txtDepartmentCode"), "mhDepartmentCode");
comboSource.Add(user.Rs.GetString("txtLocationCode"), "mhLocationCode");
comboSource.Add(user.Rs.GetString("txtModelCode"), "mhModel");
comboSource.Add(user.Rs.GetString("txtProductCode"), "phProductCode");
comboSource.Add(user.Rs.GetString("txtShiftCode"),"shShiftCode");
comboSource.Add(user.Rs.GetString("txtSubcategory"),"phSubcategory");
cboSort1.DataSource = cboSort2.DataSource = cboSort3.DataSource = cboSort4.DataSource = comboSource;
cboSort1.DataTextField = cboSort2.DataTextField = cboSort3.DataTextField = cboSort4.DataTextField = "Key";
cboSort1.DataValueField = cboSort2.DataValueField = cboSort3.DataValueField = cboSort4.DataValueField = "Value";
cboSort1.DataBind();
cboSort2.DataBind();
cboSort3.DataBind();
cboSort4.DataBind();

Related

.Net3.5 Compact Framework filtering binding source

I'm trying to get filtering working correctly within a Compact Framework environment.
I'm doing everything manually with code, not the designer.
I have a List. I set this as my datasource to my binding source. I then set my binding source as the datasource of my datagrid.
I apply a bindingSource.filter but it has absolutely no effect.
Am I missing something or is the compact framework just this poor?
I've applied a hard filter here to try to force the filter...
List<Customer> customerList = controller.getCustomersList(selectedDate, view);
bs.DataSource = customerList;
customerDataGrid.DataSource = bs;
bs.Filter = string.Format("Code like '*{0}*'", "123");
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = "Customer";
DataGridTextBoxColumn codeCol = new DataGridTextBoxColumn();
codeCol.Width = 125;
codeCol.MappingName = "Code";
codeCol.HeaderText = "Code";
tableStyle.GridColumnStyles.Add(codeCol);
DataGridTextBoxColumn nameCol = new DataGridTextBoxColumn();
nameCol.Width = 265;
nameCol.MappingName = "Name";
nameCol.HeaderText = "Name";
tableStyle.GridColumnStyles.Add(nameCol);
customerDataGrid.TableStyles.Clear();
customerDataGrid.TableStyles.Add(tableStyle);
lastView = view;
lastSelectedDate = selectedDate;

Binding childitem into menu control asp.net

DataRow[] drowpar = dt.Select("Parent_Id=" + 0);
foreach (DataRow dr in drowpar)
{
MenuItem objMenuItem = new MenuItem();
objMenuItem.Text = dr["Page_Name"].ToString();
objMenuItem.NavigateUrl = dr["Page_Url"].ToString();
MenuBar.Items.Add(objMenuItem);
}
foreach (DataRow dr in dt.Select("Parent_Id >" + 0))
{
MenuItem objMenuItem = new MenuItem();
objMenuItem.Text = dr["Page_Name"].ToString();
objMenuItem.NavigateUrl = dr["Page_Url"].ToString();
//MenuBar.FindItem(dr["Parent_Id"].ToString()).ChildItems.Add(objMenuItem);
MenuBar.FindItem(dr["Parent_Id"].ToString()).ChildItems.Add(objMenuItem);
//MenuBar.Items.Add(objMenuItem);
}
i am binding asp.net menu control using database and getting this below in childitem binding to menu
Object reference not set to an instance of an object.
MenuBar.FindItem(dr["Parent_Id"].ToString()).ChildItems.Add(objMenuItem);
That error message only happens for specific situations, and the possible reasons are:
objMenuItem is null - which obviously in your code it is not
dr["Parent_Id"] is null, and calling ToString() causes the error
MenuBar.FindItem(dr["Parent_Id"].ToString()) - this isn't finding the item with the given parent ID
The ChildItems collection on the menu item is null
If you want to be really sure where the object is not null, then you can do the following:
var id = dr["Parent_ID"].ToString();
var menuItem = MenuBar.FindItem(id);
if (menuItem != null)
menuItem.ChildItems.Add(objMenuItem);
Having the code together masks where the actual error occurs. Note, there is one other scenario where i didn't account for, which is the error is within the MenuBar itself, and it's masked. Without seeing the full stack trace, it's hard to tell. If you can post that, we can isolate it further.

Dynamically creating ASP.NET form controls

I have a form which, based on the answers given in the prior page, can have about 10 different variations in the combination of fields (most are the same, but several change). I decided rather than making 10 separate pages, I would try to make it dynamic. Eventually this will pull the form setup from a database, but for now I'm just trying to get the dynamic part to work. The following code kinda works, but it's giving me a weird result.
private void AddTestControls()
{
var newbox = new TextBox();
newbox.ID = "FirstBox";
newbox.Text = "This is dynamic";
newbox.CssClass = "stepHeader";
DynamicDiv1.Controls.Add(newbox);
var newlit = new Literal();
newlit.ID = "FirstLit";
newlit.Text = ".<br/>.";
DynamicDiv1.Controls.Add(newlit);
newbox.ID = "SecondBox";
newbox.Text = "This is also dynamic";
newbox.CssClass = "step";
DynamicDiv1.Controls.Add(newbox);
}
I've stepped through it and all the properties are getting set correctly, but when the page finally renders, only the SecondBox control is visible. There is no trace of the FirstBox. If I change it so that SecondBox is its own object (newebox2 for example) then both are visible, but with how I was thinking that I would ultimately do the form from the database, this could complicate things. I don't understand why the textbox object has to be recreated in order to add it to the Div's collection of controls. Am I going about this all wrong, or just missing a step somewhere?
Your "SecondBox" are overwriting the "FirstBox" newbox since it's still holding a reference to it. Create a new TextBox for the second box:
var newbox = new TextBox();
newbox.ID = "FirstBox";
newbox.Text = "This is dynamic";
newbox.CssClass = "stepHeader";
DynamicDiv1.Controls.Add(newbox);
var newlit = new Literal();
newlit.ID = "FirstLit";
newlit.Text = ".<br/>.";
DynamicDiv1.Controls.Add(newlit);
// Create a new TextBox
var secondBox = new TextBox();
secondBox.ID = "SecondBox";
secondBox.Text = "This is also dynamic";
secondBox.CssClass = "step";
DynamicDiv1.Controls.Add(secondBox);
I'm not quite sure why this could complicate things, but what you could do is create a method for creating a textbox, if that's easier:
TextBox CreateTextBox(string id, string text, string cssClass)
{
var box = new TextBox();
box.ID = id;
box.Text = text;
box.CssClass = cssClass;
return box;
}
And then
var newBox = CreateTextBox("FirstBox", "This is dynamic", "stepHeader");
DynamicDiv1.Controls.Add(newBox);
What's how it suppose to work. newbox1 is a reference so after the first time it's added to DynamicDiv1, it's there and if you change its Text, then the Text will be changed. You may find this SO useful. This SO demostrates the same issue you are having.

Find ListBoxes in ASP .NET

i have created dynamic listboxes (4 to 10) in ASP.NET.
and my question is , How do i find the dynamically created listboxes using c#?
thanks
Sure... and i appreciate your help . below code i am using for creating dynamic LB
protected void btndyfilter_Click(object sender, EventArgs e)
{
int numberOfListBox = lbFilter.GetSelectedIndices().Length;
string lbname = lbFilter.SelectedValue;
for (int i = 0; i < numberOfListBox; i++)
{
ListBox listb = new ListBox();
ListItem lItem = new ListItem();
listb.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Multiple;
listb.Height = 150;
listb.Width = 200;
lItem.Value = i.ToString();
lItem.Text = lbname;
listb.Items.Add(lItem);
panFilter.Controls.Add(listb);
//once we created the LB dynamically i need to populate each LB with the corresponding values
connstr2 = System.Configuration.ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
conn2.ConnectionString = connstr2;
conn2.Open();
CubeCollection CubeList = conn2.Cubes;
string cb = ddlCubeList.SelectedItem.Text;
//need to remove the Hardcoded Code
foreach (Member dimem in CubeList[cb].Dimensions["Date"].Hierarchies["Calendar Date"].Levels["Date"].GetMembers())
{
ListItem Memlist = new ListItem();
Memlist.Text = dimem.UniqueName;
lbFilter.Items.Add(Memlist);
}
}
panFilter.Visible = true;
panCubeDef.Visible = true;
}
so this will create the LB i believe :)... and Inside the commented code i need to use to populate for each LB item ..perhaps it bit hardcoded which i need to remove. so i all dynamic LBs are populated then the selected items from all LBs will come into the where clause in my MDX query..hope i did not confuse you
There is 2 way either you can store dynamic control detail with dictionary or just find when you want to use it using some code like this
Control GetControlByName(string Name)
{
foreach(Control c in this.Controls)
if(c.Name == Name)
return c;
return null;
}
while generating ListBox dynamically, give ListBox ID as:
lstBoxNo1, lstBoxNo2. lstBoxNo3 etc. where 1,2,3(no) will be from count.
like
int count=1;
generate listbox control
listboxid=lastBoxNo+count;
count++
`by doing this, u have control over id's.
else use
http://stackoverflow.com/questions/3731007/using-findcontrol-to-find-control
using this link to understand findcontrol.
The points that you wont to find that dynamic controls are.
The moment you first render the page.
On every other post back.
In the case of 1, then you better keep a variable on your page that keep that creations.
In the case of 2, when you have post back, you need to store somehow the creations of your control in the page when you render it. One good place is to keep that information on the viewstate.
You can also on the post back, just to check if you have any post back valued from controls that you have named with a serial numbering starting from 1, eg You start looking if you have post back from ControlName_1, then ControlName_2, and when you not found any other value you end.

Changing GridView column properties from code-behind

I am creating a GridView in a method like so:
GridView gridView = new GridView();
gridView.DataSource = reportData.Tables[0];
gridView.DataBind();
I am later exporting it to Excel and it works great. The columns are being auto-generated from my source data. I would like to change the DataFormatString property of some of the columns however after I databind and before I export to Excel. I can't seem to find the correct property to change. Can anybody point me in the right direction?
According to AutoGenerateColumns documentation:
This option provides a convenient way
to display every field in the data
source; however, you have limited
control of how an automatically
generated column field is displayed or
behaves.
Note: Automatically
generated bound column fields are not
added to the Columns collection.
I tired looking for these AutoGeneratedFields with no luck.
I can think of several options to achieve that (from worst to best):
Add an event to the grid (like RowDataBound), this will give you access to the rows' cells, but isn't too convenient.
Don't use AutoGeneratedField Create these columns manually, as in:
BoundField dateField = new BoundField();
dateField.HeaderText = "Date";
dateField.DataField = "date";
dateField.DataFormatString = "{0:MMMM, yyyy}";
gridView.Columns.Add(dateField);
This options gives you bes control over titles.
Add another layer for data formatting and presentation. This is probably the best option. Also, that way you don't have to use DataTables, a GridView can by bound to any collection of objects with public properties (eg, to a List<Employee)), and AutoGeneratedField turns them into columns.
I think this is the best option. Suppose you could access the auto columns, what then? You'd have to search for a column based on its name or index, which seems very messy, and increases coupling.
And, as a last note, you should think about creating Excel files by using the API. It's not as easy, but HTML XLS files are less compatible with Excel 2007 - it displays a warning message that the format of the file is incompatible with the extension, and worse, the file brakes if it is opened and saves (can be Save As though), making your files less user-friendly.
For example:
String newDataFormatString = "{0:d}";
BoundField bf = gridView.Columns[Index] as BoundField;
if (bf != null) {
bf.DataFormatString = "{0}"; // workaround to sync with ViewState (it's documented)
bf.DataFormatString = newDataFormatString;
}
This is the issue of how asp.net works. When you create some controls (columns) in a method and set this controls set to user, the next time user post backs data to you, you do not have access to those columns since they … do not exists. Every time you display your site, a brand new object (instance) is created.
The only way to be able to get data in post back from previously created controls is to create controls in Page_Init method…
Here's an extract from a GridView exporter I wrote that converts controls in a GridView into literals that are re-formated. It might be of some help:
/// <summary>
/// Parses and cleans up data from the GridView controls collection
/// to make the data more suitable for Exported
/// </summary>
/// <param name="gv">The GridView to parse</param>
private void CleanUpControls(Control gv)
{
Literal l = new Literal();
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof (LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
ReplaceWithLiteral(gv, l, i);
}
else if (gv.Controls[i].GetType() == typeof (ListControl))
{
l.Text = (gv.Controls[i] as ListControl).SelectedItem.Text;
ReplaceWithLiteral(gv, l, i);
}
else if (gv.Controls[i].GetType() == typeof (CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
ReplaceWithLiteral(gv, l, i);
}
else if (gv.Controls[i].GetType() == typeof (BooleanImage))
{
l.Text = (gv.Controls[i] as BooleanImage).Value ? "True" : "False";
ReplaceWithLiteral(gv, l, i);
}
else if (gv.Controls[i].GetType().ToString() == "System.Web.UI.WebControls.PagerTable")
ReplaceWithLiteral(gv, l, i);
else if (gv.Controls[i].GetType() == typeof (HyperLink))
{
HyperLink hl = gv.Controls[i] as HyperLink;
if (MakeHyperLinksAbsolute)
{
if (hl != null)
hl.NavigateUrl = UrlHelper.MakeAbsoluteUrl(hl.NavigateUrl);
}
switch (TreatHyperLinksAs)
{
case HyperLinkMode.Text:
l.Text = hl.Text;
ReplaceWithLiteral(gv, l, i);
break;
case HyperLinkMode.NavigateUrl:
if (hl != null) l.Text = hl.NavigateUrl;
ReplaceWithLiteral(gv, l, i);
break;
case HyperLinkMode.ToolTip:
l.Text = hl.ToolTip;
ReplaceWithLiteral(gv, l, i);
break;
case HyperLinkMode.TextAndLink:
l.Text = String.Format("{0} ({1})", hl.Text, hl.NavigateUrl);
ReplaceWithLiteral(gv, l, i);
break;
case HyperLinkMode.HyperLink:
break;
}
}
if (gv.Controls[i].HasControls())
CleanUpControls(gv.Controls[i]);
}
}

Resources