Why Itemscontrol is inconsistent with item source in datagrid wpf? - data-binding

When First time I open the form, datagrid shows data but when I open other form and again open this form this it gives error Itemscontrol is inconsistent with item source
This is my Datagrid in which is used to bind the list.
```
<DataGrid.Columns>
<DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTextColumn Header="Description" Binding="{Binding Description}" Foreground="Black" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>```
here on form load function , the datagrid loads.
{
// dtGrid1.Items.Clear();
DataTable dt_Grup = new DataTable();
DataTable dt_Type = new DataTable();
try
{
dt_Grup = dal.Select();
for(int i=0; i< dt_Grup.Rows.Count; i++)
{
FeeGroupControlShowBLL ck = new FeeGroupControlShowBLL();
dt_Type = dal.Select1("SELECT tblFeeType.Fee_Type_Name, tblFeeTypeGroup.Amount from tblFeeTypeGroup inner join tblFeeType on tblFeeTypeGroup.Fee_TypeID = tblFeeType.Fee_Type_ID where Fee_GroupID = '" + dt_Grup.Rows[i][0].ToString() + "'");
ck.groupName = dt_Grup.Rows[i][1].ToString();
ck.Description = dt_Grup.Rows[i][2].ToString();
for (int j = 0; j < dt_Type.Rows.Count; j++)
{
string Type_Amount = (string)dt_Type.Rows[j][0] + " Rs" +(string)dt_Type.Rows[j][1];
ck.FeeTypeName.Add(Type_Amount);
}
b.Add(ck);
}
dtGrid1.ItemsSource = b;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
db.con.Close();
}
}```

Related

Database driven menu is too slow

in ASP.Net using C#, I am populating an ASP.Net menu control from database dynamically. I am trying to make those items unusable which have some child items below them. This is to ensure that on mobile, where we dont have a mouse to hover, on clicking the parent menu item, user will surely get child items in stead of a postback. The code below is working fine but with a drawback, it takes too much time to load and in the mean time shows a bad result by displaying all the items (all parent + all child) vertically in a single view.
SqlCommand com = new SqlCommand("SELECT * FROM menutab order by sno", c.con);
if(c.con.State == ConnectionState.Closed)
c.con.Open();
da = new SqlDataAdapter(com);
table = new DataTable();
da.Fill(table);
parents = new int[table.Rows.Count];
for (int i = 0; i < table.Rows.Count; i++)
if (table.Rows[i].ItemArray.GetValue(2).ToString() != String.Empty)
parents[i] = Convert.ToInt32(table.Rows[i].ItemArray.GetValue(2).ToString());
DataRow[] drowpar = table.Select("menu_parent = " + 0);
view = new DataView(table);
view.RowFilter = "menu_parent is NULL";
foreach (DataRowView row in view)
{
MenuItem menuItem = new MenuItem(row["item"].ToString(), row["sno"].ToString());
//menuItem.NavigateUrl = row["menu_url"].ToString();
for (int i = 0; i < parents.Length; i++)
{
if (Convert.ToInt32(row["sno"].ToString()) == parents[i])
{
menuItem.Selectable = false;
}
}
NavigationMenu.Items.Add(menuItem);
AddChildItems(table, menuItem);
}
private void AddChildItems(DataTable table, MenuItem menuItem)
{
DataView viewItem = new DataView(table);
viewItem.RowFilter = "menu_parent=" + menuItem.Value;
foreach (DataRowView childView in viewItem)
{
MenuItem childItem = new MenuItem(childView["item"].ToString(), childView["sno"].ToString());
//childItem.NavigateUrl = childView["menu_url"].ToString();
for (int i = 0; i<parents.Length; i++)
{
if (Convert.ToInt32(childView["sno"].ToString()) == parents[i])
{
childItem.Selectable = false;
}
}
menuItem.ChildItems.Add(childItem);
AddChildItems(table, childItem);
}
}
Can this process be more faster and reliable with some other code implementation?
Database driven menu will surely show some lag in loading it for the first time and it depends on the speed of your web server too. However, the following code will help you in reducing the load time:
DataRow[] drowpar = table.Select("menu_parent = " + 0);
foreach (DataRow row in drowpar)
{
MenuItem menuItem = new MenuItem(row["item"].ToString(), row["sno"].ToString());
NavigationMenu.Items.Add(menuItem);
AddChildItems(table, menuItem);
}
private void AddChildItems(DataTable table, MenuItem menuItem)
{
DataView viewItem = new DataView(table);
viewItem.RowFilter = "menu_parent=" + menuItem.Value;
foreach (DataRowView childView in viewItem)
{
MenuItem childItem = new MenuItem(childView["item"].ToString(), childView["sno"].ToString());
menuItem.Selectable = false;
menuItem.ChildItems.Add(childItem);
AddChildItems(table, childItem);
}
}
If you are doing other tasks on page_load, make sure you write the menu code at beginning so that server starts the processing with menu and then works on other code.
Hope this helps.

why when unchecking checkbox - checkedChanged event doesn't execute

In my function createCheckboxes() I dynamically create checkboxes - all of them with assigned checkedChanged event.
In the event handler i test if the checkbox is checked and if so I sore the value attribute in a session.
But for example if a client decides to check one checkbox and alue is added to the session, but then he suddenly decides that he want to uncjheck that checbox - so I should delete this value from the arraylist and then from the session.
The big problem is that it seems that when unchecking the Checkedchanged event handler is never executed and this code is never executed
else if (!chk.Checked)
{
lblProba.Text += "You wll be delited";
for (int i = 0; i < element.Count; i++)
{
if (element[i].ToString().Equals(chk.InputAttributes["value"]) == true)
element.Remove(element[i]);
}
}
My full code
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
element.Add(chk.InputAttributes["value"]);
}
else if (!chk.Checked)
{
lblProba.Text += "You wll be delited";
for (int i = 0; i < element.Count; i++)
{
if (element[i].ToString().Equals(chk.InputAttributes["value"]) == true)
element.Remove(element[i]);
}
}
for (int t = 0; t < element.Count; t++)
{
Session["chk"]+= element[t].ToString();
}
}
protected void createCheckboxes()
{
chkddlchange = true;
int numTourists = 2;
for (int i = 0; i < numTourists; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblAccomodation" + (i + 1).ToString();
myLabel.Text = "Настаняване Турист" + (i + 1).ToString();
Page.FindControl("form1").Controls.Add(myLabel);
DropDownList myDropDownList = new DropDownList();
myDropDownList.ID = "ddlTourist" + i.ToString();
Page.FindControl("form1").Controls.Add(myDropDownList);
Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd= cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
CheckBox mycheckbox = new CheckBox();
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Text = rd["Extra_Charge_Description"].ToString();
mycheckbox.InputAttributes.Add("value", rd["Extra_Charge_ID"].ToString());
mycheckbox.AutoPostBack = true;
mycheckbox.EnableViewState =true ;
mycheckbox.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(mycheckbox);
s++;
}
//myche.Add(mycheckbox.Items[s].Text);
}//End of try
catch (Exception ex)
{ }
}//end of for
}
}
}
Have you mentioned Autopostback=true while creating your checkbox? If not than please do it and see if it works or not.

How can itereate through checkboxes using forlopp in C#?

I need to check whether the checkbox values are ticked or not using 'for' loop.
CheckBox chkBox = (CheckBox)tab_patients.Controls[chk + i];
from searches i got this line. what this tab_patients denote ?`
string chk = "CheckBox";
for (int i = 1; i < 13; i++)
{
for (int k = 1; k < 4; k++)
{
// CheckBox chkBox = (CheckBox)tab_patients.Controls[chk + i];
CheckBox cb = (CheckBox)this.Page.Form.FindControl("chk"+i.ToString());
if(cb.Checked==true)
{
check = i + "0" + k;
}
}}
Make your life easier and create the checkboxes with checkboxlists: http://msdn.microsoft.com/de-de/library/system.web.ui.webcontrols.checkboxlist.aspx
<asp:CheckBoxList ID="SomeElement" runat="server"
AutoPostBack="true"
RepeatColumns="4"
EnableViewState="true">
</asp:CheckBoxList>
With the Repeatcolumns property you are telling the element, that you infact want 4 columns, so the control will devide your 32 elements by 4 and group those checkboxes by the pack of 8.
After this, you can iterate through every list like this:
foreach(var cb in checkboxlistID)
{
if(cb.Checked)
{
//do something
}
}
On top of that, here is some old code showing you how to fill a checkboxlist with data fetched from a SQL-query. You can ignore the if expression, which is checking if there is cached data, from which to fill all the checkboxes.
using (OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
string Query = #"SELECT * from level";
OleDbCommand command = new OleDbCommand(Query, connection);
if (Session["SavedLevelItems"] != null)
{
CheckBoxListLevel.Items.Clear();
List<ListItem> SessionList = (List<ListItem>)Session["SavedLevelItems"];
foreach (var item in SessionList)
{
try
{
CheckBoxListLevel.Items.Add(item);
}
catch { }
}
}
else
{
connection.Open();
CheckBoxListLevel.DataTextField = "bez_level";
CheckBoxListLevel.DataValueField = "id_level";
OleDbDataReader ListReader = command.ExecuteReader();
CheckBoxListLevel.DataSource = ListReader;
CheckBoxListLevel.DataBind();
ListReader.Close(); ListReader.Dispose();
}
}

Dynamically add checkboxlist into placeholder and get the checked value of the checkboxlist

I am creating an admin Page, in which checkboxlist(User list from DB)is to be created dynamically and its the checked users value is retrieved.
There are different types of users, so it is distinguised groupwise.
Now first a panel is defined, the checkboxlist is created dynamically and placed inside the panel, then the panel is placed inside a Placeholder.
What Iam doing here is placing the checkboxlist inside the panel, then the panel inside the placeholder. So the values of the Checkboxlist is not retrieved, due to the panel it doesnt get the checkboxlist and it doesn't loop through the Checkboxlist.
What I have done is.
private void AddControl(string pUserGrp, int pUserGrp_Id, int pName)
{
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
User us = new User();
us.OrderBy = "Order By User_Name";
us.WhereClause = "Where UserRole_Id = " + pUserGrp_Id ;
chkList.ID = "ChkUser" + pName ;
chkList.AutoPostBack = true;
chkList.Attributes.Add("onClick", "getVal(ChkUser" + pName + ");");
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
chkList.Attributes.Add("onClick", "getVal(this);");
Panel pUser = new Panel();
if (pUserGrp != "")
{
pUser.GroupingText = pUserGrp ;
chk.Text = pUserGrp;
}
else
{
pUser.GroupingText = "Non Assigned Group";
chk.Text = "Non Assigned group";
}
pUser.Controls.Add(chk);
pUser.Controls.Add(chkList);
Place.Controls.Add(pUser);
}
private void setChecked(int pPageGroupId)
{
ArrayList arr = new ArrayList();
PageMaster obj = new PageMaster();
obj.WhereClause = " Where PageGroup_Id = " + pPageGroupId;
arr = obj.GetPageGroupUserRights(null);
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
if (chkList != null)
{
for (int i = 0; i < chkList.Items.Count; i++)
{
if (arr.Count > 0)
{
int ii = 0;
while (ii < arr.Count)
{
PageMaster oCand = (PageMaster)arr[ii];
if (oCand.User_Name == chkList.Items[i].Text)
{
if (!chkList.Items[i].Selected)
{
chkList.Items[i].Selected = true;
}
}
ii++;
oCand = null;
}
}
}
}
}
public string GetListCheckBoxText()
{
StringBuilder sbtext = new StringBuilder();
foreach (Control c in Place.Controls)
{
if (c.GetType().Name == "CheckBoxList")
{
CheckBoxList cbx1 = (CheckBoxList)c;
foreach (ListItem li in cbx1.Items)
{
if (li.Selected == true)
{
sbtext.Append(",");
sbtext.Append(li.Value);
}
else
{
sbtext.Append(li.Value);
}
}
}
}
return sbtext.ToString(); }
It doesnt get through the Checkboxlist control in the setChecked(), also doesnt loop through the GetListCheckBoxTest().
Anyone can plz help me.
Regards
The problem is that you are trying to find a control (in setChecked) without setting the Name property. You are using this:
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
But where is this in AddControl?
chkList.Name = "ChkUser";
And in GetListCheckBoxText instead of...
if (c.GetType().Name == "CheckBoxList")
...use this:
if (c.GetType()== typeof(CheckBoxList))

Gathering Data: Dynamic Text Boxes

Edit: if someone could also suggest a more sensible way to make what I'm trying below to happen, that would also be very appreciated
I'm building an multiPage form that takes a quantity (of product) from a POST method, and displays a form sequence relying on that number. when the user goes to the next page, the form is supposed to collect this information and display it (for confirmation), which will then send this info to a service that will supply URL's to display.
Needless to say, I'm having problems making this work. Here is the relevant parts of my (anonymised) code:
public partial class foo : System.Web.UI.Page
{
Int quantityParam = 3;
ArrayList Users = new ArrayList();
//the information for each user is held in a hashtable the array list will be an array list of the user hashtables
protected void Page_Init(object sender, EventArgs e)
{
if(null != Request["quantity1"])
{
this.quantityParam = Request["quantity1"];
}
}
protected void Page_Load(object sender, EventArgs e)
{
int quantity = this.quantityParam;
if(quantity < 1){ mviewThankYou.SetActiveView(View4Error);}
else
{ //create a form for each user
mviewThankYou.SetActiveView(View1EnterUsers);
for(int user = 0;user < quantity; user++)
{
createUserForm(user);
}
}
}
protected void BtnNext1_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
for(int i = 0; i < quantity; i++)
{
String ctrlName = "txtUser" + i.ToString();
String ctrlEmail = "txtEmail" + i.ToString();
TextBox name = (TextBox)FindControl(ctrlName);
TextBox email = (TextBox)FindControl(ctrlEmail);
/*BONUS QUESTION: How can I add the Hashtables to the Users Array without them being destroyed when I leave the function scope?
this is where the failure occurs:
System.NullReferenceException: Object reference not set to an instance of an object. on: "tempUser.Add("name",name.Text);
*/
Hashtable tempUser = new Hashtable();
tempUser.Add("name",name.Text);
tempUser.Add("email",email.Text);
this.Users.Add(tempUser);
}
for(int i = 0; i < quantity; i++)
{
v2Content.Text +="<table><tr><td>Name: </td><td>"+
((Hashtable)Users[i])["name"]+
"</td></tr><tr><td>Email:</td><td>"+
((Hashtable)Users[i])["email"]+
"</td></tr></table>";
}
mviewThankYou.SetActiveView(View2Confirm);
}
}
private void createUserForm(int userNum){
DataTable objDT = new DataTable();
int rows = 2;
int cols = 2;
//create the title row..
TableRow title = new TableRow();
TableCell titleCell = new TableCell();
formTable.Rows.Add(title);
Label lblUser = new Label();
lblUser.Text = "<b>User "+ (userNum+1) + "</b>";
lblUser.ID = "lblTitle"+ userNum;
titleCell.Controls.Add(lblUser);
title.Cells.Add(titleCell);
for(int i = 0; i < rows; i++)
{
TableRow tRow = new TableRow();
formTable.Rows.Add(tRow);
for(int j = 0; j < cols; j++)
{
TableCell tCell = new TableCell();
if(j == 0){
Label lblTitle = new Label();
if(i == 0){
lblTitle.Text = "User Name:";
lblTitle.ID = "lblUser" + userNum;
}
else{
lblTitle.Text = "User Email:";
lblTitle.ID = "lblEmail" + userNum;
}
tCell.Controls.Add(lblTitle);
} else {
TextBox txt = new TextBox();
if(i==0){
txt.ID = "txtUser" + userNum;
}
else{
txt.ID = "txtEmail" + userNum;
}
RequiredFieldValidator val = new RequiredFieldValidator();
val.ID = txt.ID + "Validator";
val.ControlToValidate = txt.UniqueID;
val.ErrorMessage = "(required)";
tCell.Controls.Add(txt);
tCell.Controls.Add(val);
}
tRow.Cells.Add(tCell);
}//for(j)
}//for(i)
//create a blank row...
TableRow blank = new TableRow();
TableCell blankCell = new TableCell();
formTable.Rows.Add(blank);
Label blankLabel = new Label();
blankLabel.Text = " ";
blankLabel.ID = "blank" + userNum;
blankCell.Controls.Add(blankLabel);
blank.Cells.Add(blankCell);
}//CreateUserForm(int)
Sorry for the gnarly amount of (amateur code). What I suspect if failing is that FindControl() is not working, but I can't figure out why...
if any help can be given, I'd be very greatful.
Edit: showing the error might help:
Error (Line 112)
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 111: Hashtable tempUser = new Hashtable();
Line 112: tempUser.Add("name",name.Text);
Line 113: tempUser.Add("email",email.Text);
Line 114: this.Users.Add(tempUser);
You problem comes in the fact you are reloading the form every time in Page_Load. Make sure you only load the dynamic text boxes once and you will be able to find them when you need them for confirmation. As long as Page_Load rebuilds, you will not find the answer, and risk not finding anything.
I figured it out:
FindControl() works as a direct search of the children of the control it's called on.
when I was calling it, it was (automatically) Page.FindControl() I had nested the table creation inside a field and a Table control
when I called tableID.FindControl() it found the controls just as it should.
Thanks for the help, Gregory, and for all the comments everyone.
-Matt

Resources