DropDownList in C#, getting DropDownList items overflow after every time using selecting an item - ddl

well the problem is that i am trying to get DDL to:
1. Recive catagories from a DB tabel - working
2. OnChange select from a different table the products by the item in the DDL - working
had a problem with No1 but fixed that problem. i found out that to get No1 working i have to use postback. did that and every thing in that part is working well and actualy every thing is working...but my hug problem (and i cant find any good answer for it) is that every time i change the item i a getting all the times all over again(i have initialy 8 item - secont time 16 - 24 etc....)
tried to use: ddlCatagories.Items.Clear();
when i use that i am not getting any duplicates but then, i am not getting any thing, it takes the first catagory from the list every time, no matter what i chose in the list..
trying to figure it out for the past week...please help :-)
public partial class selectNamesFromCatagories : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ddlCatagories.Items.Clear();
SqlDataReader dr = DbHelper.ExecuteReader(
sqlConn1.home,
"spSelectNamesFromCatagories");
while (dr.Read())
{
ListItem li = new ListItem(dr["CategoryName"].ToString());
ddlCatagories.Items.Add(li);
}
dr.Close();
}
protected void ddlCatagories_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataReader dr = DbHelper.ExecuteReader(
sqlConn1.home,
"spProductsByCatagoryID",
new SqlParameter("#catName", ddlCatagories.Text)
);
while (dr.Read())
{
TableRow tr = new TableRow();
for (int i = 0; i < dr.FieldCount; i++)
{
TableCell td = new TableCell();
td.Text = dr[i].ToString();
tr.Controls.Add(td);
}
tblProductsByCatagories.Controls.Add(tr);
}
}
}

Only populate the DropDownList on first load by checking whether the page has not posted back ie.
if (!Page.IsPostBack)
{
// Populate list
}

I agree with Dan and would add the following as well if you have any ajax enabled controls as they may generate callbacks.
if (!Page.IsPostBack && !Page.IsCallBack)
{
// Populate list
}

Related

Infragistics XamGrid: How to prevent column filter from showing time?

We are using DateTime columns with time, but need the (excel style distinct elements) column filter to show only the dates, without time. Is that possible?
I found an article at Infragistics which describes how to add a custom filter but not how to change an existing one.
Got the following code snipped from infragistics support (thanks Tacho!):
private void XamDataGrid_RecordFilterDropDownOpening(object sender, RecordFilterDropDownOpeningEventArgs e)
{
if (e.Field.DataType == typeof(DateTime))
{
List<FilterDropDownItem> cellValues = e.DropDownItems.Where(i => i.IsCellValue).ToList();
foreach (FilterDropDownItem item in cellValues)
e.DropDownItems.Remove(item);
foreach (FilterDropDownItem item in cellValues)
{
item.DisplayText = (item.Value as DateTime?).Value.ToString("yyyy/MM/dd");
if (!e.DropDownItems.Contains(e.DropDownItems.FirstOrDefault(i => i.DisplayText == item.DisplayText)))
{
var newItem = new FilterDropDownItem(new Infragistics.Windows.Controls.ComparisonCondition(
Infragistics.Windows.Controls.ComparisonOperator.Contains, item.DisplayText), item.DisplayText);
e.DropDownItems.Add(newItem);
}
}
}
}

How to create separate DetailTable on each row in a RadGrid?

I have a telerik radgrid where columns and detail tables are declared like:
<telerik:RadGrid>
<Columns>
<telerik:GridBoundColumn/>
<telerik:GridBoundColumn/>
</Columns>
<DetailTables>
<telerik:GridTableView
<Columns>
<telerik:GridBoundColumn/>
<telerik:GridBoundColumn/>
</Columns>
</telerik:GridTableView
</DetailTables>
</telerik:RadGrid>
Which gives a nested grid like this:
Now, what I want is to be able to specify a detail table (those sub tables) per row, programmatically.
(I cannot be sure that the columns for the nested table that comes up when I expand the line fgvbvb will be the same as the columns when expanding the line xcxcv).
I have tried, without luck in the OnDataBound handler of the radgrid (in which I omitted <DetailTables>) to access the data structure for nested tables like this:
protected void OnRadGridDataBound(object sender, EventArgs e)
{
foreach (GridDataItem item in grdActivitiesToCopy.MasterTableView.Items)
{
var dg = item.ChildItem.NestedTableViews[0];
}
}
This will overindex the array NestedTableViews because it is empty. Also, item.ChildItem.NestedTableViews has no setter.
How do I populate each row with a detail table one by one manually?
According to Telerik:
RadGrid does not support mixing declarative grid columns with grid
columns added dynamically at runtime. You should either create all the
columns in the grid programmatically, or else define them all in the
ASPX file. When creating Detail tables, it should be created in the
PageInit event.
Creating a Hierarchical Grid Programmatically:
You should follow these basic steps in order to create hierarchical
RadGrid programmatically in the code-behind (having a data source
control for data content generation):
Create the grid dynamically in the Page_Init handler of the page by
calling its constructor.
Specify the preferred settings for your grid instance through its
properties.
Create columns for the grid dynamically. Keep in mind that you have to
first set their properties and then add them to the
MasterTableView/GridTableView collection (discussed in the first
paragraph of this same topic). Thus, their ViewState will be properly
persisted (as LoadViewState is raised after the Init event of the
page).
Set the proper ParentTableRelations for the GridTableViews (along with
their MasterKeyField and DetailKeyField attributes) and DataKeyNames
for the MasterTableView/GridTableViews in the code-behind of the page.
Assign data sources (through the DataSourceID attribute) for each
table in the grid hierarchy.If you do not want to use declarative
relations, generate the data in the NeedDataSource/DetailTableDataBind
handlers of the grid. On DetailTableDataBind you can determine which
data source should be related to the currently bound GridTableView by
checking its Name/DataSourceID property. Here, the Name property must
have a unique value for each detail table (this value has to be
defined previously by the developer) and the DataSourceID is the ID of
the DataSource control responsible for the corresponding detail table
content generation.
Code Sample:
RadGrid RadGrid1 = new RadGrid();
RadGrid1.DataSourceID = "SqlDataSource1";
RadGrid1.MasterTableView.DataKeyNames = new string[] { "CustomerID" };
RadGrid1.Skin = "Default";
RadGrid1.Width = Unit.Percentage(100);
RadGrid1.PageSize = 15;
RadGrid1.AllowPaging = true;
RadGrid1.AutoGenerateColumns = false;
//Add columns
GridBoundColumn boundColumn;
boundColumn = new GridBoundColumn();
boundColumn.DataField = "CustomerID";
boundColumn.HeaderText = "CustomerID";
RadGrid1.MasterTableView.Columns.Add(boundColumn);
boundColumn = new GridBoundColumn();
boundColumn.DataField = "ContactName";
boundColumn.HeaderText = "Contact Name";
RadGrid1.MasterTableView.Columns.Add(boundColumn);
//Detail table - Orders (II in hierarchy level)
GridTableView tableViewOrders = new GridTableView(RadGrid1);
tableViewOrders.DataSourceID = "SqlDataSource2";
tableViewOrders.DataKeyNames = new string[] { "OrderID" };
GridRelationFields relationFields = new GridRelationFields();
relationFields.MasterKeyField = "CustomerID";
relationFields.DetailKeyField = "CustomerID";
tableViewOrders.ParentTableRelation.Add(relationFields);
RadGrid1.MasterTableView.DetailTables.Add(tableViewOrders);
Please refer to this help article for more details:
http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/defining-structure/creating-a-radgrid-programmatically#creating-a-hierarchical-grid-programmatically
First of all , because of the life cicle of a asp page. You can't access to a event on a detail table.
If you need to access detail tables , items etc ..
You need to add an method to the PreRender in the MasterTableView like this:
<MasterTableView DataSourceID="myDataSource"
AllowMultiColumnSorting="True"
DataKeyNames="Key1,Key2,KeyN"
HierarchyDefaultExpanded="True"
OnPreRender="Unnamed_PreRender" >
The method will recursively iterate through the grid.
The way you do it can change depending on your HieararchyLoadMode.
So this is my way to do it, easiest way exist if you are on Client or Serverbind mode.
Traversing and load mode by the telerik doc .
I'm pretty sure you don't want to :
"populate each row with a detail table one by one manually"
You want to have Multiple table at a Sub Level in your grid and display the rigth one programmatically.
And this is can be done in two easy step:
1/. Create every Detail table in your apsx page.
Please refer to this documentation for more information :
Several tables at a level
2/. Handle the display:
protected void Unnamed_PreRender(object sender, EventArgs e)
{
if (!IsPostBack) myControler(MASTERGRID.MasterTableView);
}
private void myControler(GridTableView gridTableView)
{
GridItem[] nestedViewItems = gridTableView.GetItems(GridItemType.NestedView);
foreach (GridNestedViewItem nestedViewItem in nestedViewItems)
{
foreach (GridTableView nestedView in nestedViewItem.NestedTableViews)
{
if (nestedView.Name == "mytable12" && nestedView.Items.Count == 0)
{ HideExpandColumn(nestedView, nestedView.ParentItem["ExpandColumn"]); }
else if (nestedView.Name == "mytable23")
{
if (nestedView.Items.Count == 0)//
HideExpandColumn(nestedView, nestedView.ParentItem["ExpandColumn"]);
else
{ }
}
if (nestedView.HasDetailTables)
{ myControler(nestedView); }
}
}
}
private void HideExpandColumn(GridTableView _GNVI, TableCell _cell)
{
if (_cell.Controls.Count > 0)
{
_cell.Controls[0].Visible = false;
_cell.Text = " ";
}
_GNVI.Visible = false;
}
You can hide a detail table using :
HideExpandColumn(nestedView, nestedView.ParentItem["ExpandColumn"]);
Or you can hide the parent of the detail table you tested using the detail table that is in param of the controler :
HideExpandColumn(gridTableView, nestedView.ParentItem["ExpandColumn"]);
HideExpandColumn will hide the expand control that stay sometimes even if you hide th detail table.
Bonus: If you need to access to a control in a detail table.
You can use this:
public static class ControlExtensions
{
public static Control FindIt(this Control control, string id)
{
if (control == null) return null;
Control ctrl = control.FindControl(id);
if (ctrl == null)
{
foreach (Control child in control.Controls)
{
ctrl = FindIt(child, id);
if (ctrl != null) break;
}
}
return ctrl;
}
}
Calling it in your controler like this :
else if (nestedView.Name == "DetailPV")
{
if (nestedView.Items.Count == 0)
HideExpandColumn(gridTableView, nestedView.ParentItem["ExpandColumn"]);
else
{
RadLabel ctrl = (RadLabel)this.FindIt("RadLabel11");
ctrl.Text += "<b>" + nestedView.Items.Count.ToString() + "</b>";
}

Value of Column Name DataGridView

I'm using Visual Studio 2010 and i'm developing a windows form. Right now I'm using a data grid view and i want to write some functions that would allow you to automaticlly edit the datagrid by just changing the text in the Datagrid view. Right now, I am able to get the actual value but I need the value of the column in order to use it as a parameter when i use ADO.net here's what my code looks like now
private void dgv_DataLookup_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DialogResult dr;
dr = MessageBox.Show("Are you sure you want to edit this field?", "Edit Cell", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
DataGridViewCell editItemCell = dgv_DataLookup[dgv_DataLookup.CurrentCell.RowIndex, dgv_DataLookup.CurrentCell.ColumnIndex];
string editItem = editItemCell.Value.ToString();
}
}
this here gets me the value of the current cell that is currently selected. I tried doing something like this
DataGridViewColumns columnCells = dgv_DataLookup.CurrentCell.ColumnIndex.Value.ToString()... something that would represent this but actual code. thanks!
According to what I understand you want to edit the value within a field, you can choose the value in this way.
private void button2_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to edit this field?",Application.ProductName.ToString(),MessageBoxButtons.YesNo)== DialogResult.Yes)
{
string editItem = this.dataGridView1.Rows[this.dataGridView1.CurrentRow.Index].Cells["NameField"].Value.ToString();
}
}
Bye

Telerik RADGrid - linq and updating

Telerik's RADGrid, basing on their example on http://demos.telerik.com/aspnet-ajax/grid/examples/dataediting/programaticlinqupdates/defaultcs.aspx
Problem: I can insert and delete, however updating doesn't work. No error trapped. Data just doesn't change.
From the code below it looks like Telerik Grid is doing some kung-fu behind the scenes to wire things up. I can't see the db receiving any update statements.
Question: anything obvious I'm missing?
protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
{
var editableItem = ((GridEditableItem) e.Item);
var raceId = (Guid) editableItem.GetDataKeyValue("RaceID");
//retrive entity form the Db
var race = DbContext.races.Where(n => n.raceid == raceId).FirstOrDefault();
if (race != null)
{
//update entity's state
editableItem.UpdateValues(race);
try
{
//submit chanages to Db
DbContext.SubmitChanges();
}
catch (Exception f)
{
ShowErrorMessage(f);
}
}
}
Think I may have to go back to their example.. get their db.. and attack from that point of view.
Cheers!
Do a Rebind after your update. Trying adding
RadGrid1.DataSource = null;
RadGrid1.Rebind();
After your call to DbContext.SubmitChanges(); call, assuming you have implemented _NeedDataSource().

Can't bind a GridView to a LINQ to SQL Result

OK, I am amittedly new to LINQ and have spent the last week reading everything I could on it. I am just playing around, trying to follow some examples I have found (a PDF from Scott Gu on the topic, in fact) and I am at a complete loss. Can someone please tell me why, when I bind a GridView to the query below, using the code below, I get no data?? I can see the results while debugging, so I know they are coming back from the DB, they are just not apparently binding correctly. I read something saying you could not bind directly to the result,and that you have to use a BindingSource as an intermediate step?
Someone, please tell me what I am missing here.
protected void Page_Load(object sender, EventArgs e)
{
SwapDBDataContext db = new SwapDBDataContext();
var users = from u in db.aspnet_Users
select new
{
Name = u.UserName,
ID = u.UserId
};
GridView1.DataSource = users;
GridView1.DataBind();
}
I am just using an empty GridView. I had assumed that the binding would take care of setting up the columns to match the resulting columns from the query - was that a stupid beginners mistake?
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
You should not have to convert to a List or Array. Binding requires, at a minimum, an IEnumerable<T>, which is what your Users variable is. Anonymous types are simply pre-compile place holders for compiler generated concrete types, so you should also be able to bind to anonymous types.
Your GridView may not have the AutoGeneratedColumns property set, which is what is required to have the data source define what columns appear. Try enabling that, and see if your GridView displays your queries results.
Cant understand why this shouldn't work. I whipped together a page using (almost) your code. It works perfectly for me.
protected void Page_Load(object sender, EventArgs e)
{
BlodsockerkollenDataContext db = new BlodsockerkollenDataContext();
var members = from m in db.Members
select new { Id = m.Id, Email = m.Email };
GridView1.DataSource = members;
GridView1.DataBind();
}
I don't agree with the suggested answers stating you should use ToList(). The GridView is capable of taking and traversing an IEnumerable, and IQueryable inherits IEnumerable.
And no, there should be no need to declare a BindingSource.
Maybe you have declared something in your GridView? Mine is just empty, pulled straight in from the toolbox:
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
SwapDBDataContext db = new SwapDBDataContext();
GridView1.DataSource = from u in db.aspnet_Users
select new
{
Name = u.UserName,
ID = u.UserId
};
GridView1.DataBind();
}
Try doing
GridView1.DataSource = users.ToList();
or
GridView1.DataSource = users.ToArray();
Is possibly that the query isn't executing at all, because of deferred execution.

Resources