I create a TabPage and add on the TabPage a user control.
private void AddScriptTab(TabControl tab_contr, string tab_name, int idx)
{
TabPage tab_page = new TabPage();
UserControlScript user_contr = new UserControlScript(serial_port, ref tabs);
tab_contr.TabPages.Insert(idx, tab_page);
tab_page.Text = tab_name;
tab_page.Tag = "script";
user_contr.Dock = DockStyle.Fill;
user_contr.Tag = idx.ToString();
tab_page.Controls.Add(user_contr);
}
Now in the created TabPage I click on the button in my user control and check the tag I assigned
user_contr.Tag = idx.ToString();
private void buttonParamsLoad_Click(object sender, EventArgs e)
{
foreach (TabParams tab in tablist)
{
if (tab.Tag.ToString() == Tag.ToString())
tab.File = file_path;
}
}
But I getting an exception Tag is null.
Why?
OMG! I found the problem. I should add components in the right order.
private void AddScriptTab(TabControl tab_contr, string tab_name, int idx)
{
TabPage tab_page = new TabPage();
UserControlScript user_contr = new UserControlScript(serial_port);
tab_page.Text = tab_name;
tab_page.Tag = "script";
user_contr.Dock = DockStyle.Fill;
user_contr.Tag = idx.ToString();
tab_page.Controls.Add(user_contr);
tab_contr.TabPages.Insert(idx, tab_page);
}
I have problem with ASP.NET and dynamic controls. I have three ASCX. One of them creates two textboxes and some labels. The second containing control created if first ASCX (two textboxes and some labels). In addiction, second control also have link button named “Add Next” which on click event adding another control (two textboxes and some labels). The third ASCX control contains many the second ASCX (amount depend on SQL result). I made simple image to clarify:
The orange box contains many controls. The red box adding many black boxes on click “ADD NEXT”.
For now I use session variable to save state during recreate. For one “red box” it is working, but if I add more “red boxes”, clicking every “ADD NEXT” adding new control with textboxes and labels to every “red box” instead of in this where was clicked button “ADD NEXT”. I suppose why it is happening. Because every “red box” refers to the same Session variable, but I don’t know how to fix it. I was trying during OnClick event passing unique ID and setting this ID as session variable name, but it wasn’t working as I expected.
Could you tell me, how to manage it? How looks the best way to recreate controls, how I can manage controls individually? If something is not clear, I will clarify. Always I was finding answers in stackoverflow, but this problem has outgrow me.
Best wishes.
(Sorry for my English, it doesn’t my native language)
My code.
Code for creating textboxes and some labels (Calculator.cs):
public string FLong
{
get
{
object o = ViewState["FLong"];
if (o == null)
return String.Empty;
return (string)o;
}
set { ViewState["FLong"] = value; }
}
public string FWide
{
get
{
object o = ViewState["FWide"];
if (o == null)
return String.Empty;
return (string)o;
}
set
{
ViewState["FWide"] = value;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateControlHierarchy();
ClearChildViewState();
}
protected virtual void CreateControlHierarchy()
{
Literal row = new Literal();
row.Text = "<div class='row surface'>";
Controls.Add(row);
//Add new TextBox;
Literal col = new Literal();
col.Text = "<div class='col-xs-4'>";
Controls.Add(col);
TextBox fLong = new TextBox();
fLong.ID = "fLong";
fLong.CssClass = "form-control";
//fLong.TextChanged += new EventHandler(Calculate_TextChanged);
//fLong.AutoPostBack = true;
fLong.Text = FLong;
Controls.Add(fLong);
Literal textLong = new Literal();
textLong.Text = "<span>ft. long x</span>";
Controls.Add(textLong);
RegularExpressionValidator flongValidate = new RegularExpressionValidator();
flongValidate.ControlToValidate = "fLong";
flongValidate.ErrorMessage = "Only Numbers allowed";
flongValidate.ValidationExpression = #"\d+";
flongValidate.ForeColor = System.Drawing.Color.Red;
flongValidate.Attributes["style"] = "display:block";
Controls.Add(flongValidate);
Literal colEnd = new Literal();
colEnd.Text = "</div>";
Controls.Add(colEnd);
//Add new Textbox
Literal col2 = new Literal();
col2.Text = "<div class='col-xs-4'>";
Controls.Add(col2);
TextBox fWide = new TextBox();
fWide.ID = "fWide";
fWide.CssClass = "form-control";
fWide.Text = FWide;
Controls.Add(fWide);
Literal textWide = new Literal();
textWide.Text = "<span>ft. wide</span>";
Controls.Add(textWide);
RegularExpressionValidator fwideValidate = new RegularExpressionValidator();
fwideValidate.ControlToValidate = "fWide";
fwideValidate.ErrorMessage = "Only Numbers allowed";
fwideValidate.ValidationExpression = #"\d+";
fwideValidate.ForeColor = System.Drawing.Color.Red;
fwideValidate.Attributes["style"] = "display:block";
Controls.Add(fwideValidate);
Literal col2End = new Literal();
col2End.Text = "</div>";
Controls.Add(col2End);
Literal rowEnd = new Literal();
rowEnd.Text = "</div>";
Controls.Add(rowEnd);
}
Code handling recreating (SurfaceCalculator.cs):
private int DefaultAmountControls = 1;
private string surfaceID;
public string SurfaceID
{
get { return surfaceID; }
set { surfaceID = value; }
}
public int Visibility
{
get
{
//store the object in session if not already stored
if (Session[surfaceID] == null)
Session[surfaceID] = DefaultAmountControls;
//return the object from session
return (int)Session[surfaceID];
}
set
{
if (value <= 5)
Session[surfaceID] = value;
else
Session[surfaceID] = 5;
}
}
protected void addSurface_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
surfaceID = b.CommandArgument;
Visibility += 1;
}
protected override void OnInit(EventArgs e)
{
LinkButton addSurface = new LinkButton();
addSurface.Text = "+ Add surface";
addSurface.CommandArgument = surfaceID;
addSurface.Click += new EventHandler(addSurface_Click);
base.OnInit(e);
List<Calculator> c = Surface.Controls.OfType<Calculator>().ToList();
for (int i = 1; i <= Visibility; i++)
{
c.ElementAt(i - 1).Visible = true;
}
if (Visibility >= 5)
{
addSurface.Enabled = false;
}
Controls.Add(addSurface);
}
Code to adding many controls depending on SQL result
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var listOfProjects = //GETTING FROM SQL
if(listOfProjects != null)
{
foreach (var proj in listOfProjects)
{
Panel placeHolder = new Panel();
placeHolder.CssClass = "surface";
placeHolder.ID = "placeHolder" + proj.DocumentID;
surfacesContainer.Controls.Add(placeHolder);
SurfaceCalculator newElement = (SurfaceCalculator)LoadControl("~/PATH_TO/CONTROL.ascx");
newElement.ID = "surfaceCalculator" + proj.DocumentID;
newElement.SurfaceID = newElement.ID;
placeHolder.Controls.Add(newElement);
}
}
}
I have 2 buttons that is supposed to update the db, and when it updates the page should do a postback with the updated info, however...right now it updates in db alright, but the page doesnt update until the 2nd click, and then the clicks afterwards are alright until i clicked on anohter tab...everything happens all over again...btw the buttons are called up and down, they are dynamically created inside a template that creates the grid
so the up/down button is built right after page_load, the page_load function calls the loaddisplaygrid(or loaddynamicdisplaygrid), then in the loaddisplaygrid(or loaddynamicdisplaygrid) function it builds the template that build the buttons
//page load
protected void Page_Load(object sender, EventArgs e)
{
RadToolBarItem textbxItem = MainRadToolBar.Items.FindItemByText("textbox");
RadTextBox displayName = (RadTextBox)textbxItem.FindControl("displayName");
Session["UserID"] = getUserID();
if (!Page.IsPostBack)
{
if (Profile.ShowFilter)
{
displayMenuBar.Style["display"] = "block";
displayLineBreak.Style["display"] = "block";
}
else
{
displayMenuBar.Style["display"] = "none";
displayLineBreak.Style["display"] = "none";
}
loadDisplay();
loadTemplate();
loadTabs();
saveDefaultOneOffFilter();
checkIfEmpty();
RadTab tab = displayTabs.SelectedTab;
Profile.CurrTemplate = Profile.DefaultTemplate;
if (Profile.DefaultTemplate == dfltTempID) //new user
{
displayName.Text = User.Identity.Name + "_default";
si_display_save_button_Click();
setDefault();
Profile.CurrTemplate = Profile.DefaultTemplate;
updateStatsformat();
Response.Redirect("Display.aspx");
}
if (tab != null)
{
loadDisplayGrid(Profile.CurrTemplate);
Session["SelectedTabID"] = tab.Text;
}
}
else
{
RadTab tab = displayTabs.SelectedTab;
if (tab != null)
{
if (tab.Text == Session["SelectedTabID"].ToString())
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
loadDynamicDisplayGrid(Profile.CurrTemplate);//needs to be different, special just for postback
}
else
{
loadDisplayGrid(Profile.CurrTemplate);
Session["SelectedTabID"] = displayTabs.SelectedTab.Text;
}
//automatically saves when toolbar is not visible....
if (!Profile.ShowFilter) { si_display_save_button_Click(); }
}
}
}
/// <summary>
/// updates and loads the RadGrid for the Display page, depending on which Tab is selected
/// </summary>
private void loadDisplayGrid(int tmpid)
{
short DType = Convert.ToInt16(displayTabs.SelectedTab.Value);
GridBoundColumn column;
GridColumn columnchkbx;
GridButtonColumn columnUp;
GridButtonColumn columnDown;
GridTemplateColumn columntxtbx;
DisplayGrid.DisplayGridDataTable DisplayGridDT = new DisplayGrid.DisplayGridDataTable();
DisplayGridTableAdapters.DisplayGridTableAdapter DisplayGridTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
//update statsformat for the user if necessary
if (Profile.CurrTemplate != 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDB_ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("UpdateNewStat", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#userid", SqlDbType.UniqueIdentifier).Value = getUserID();
command.Parameters.Add("#tempid", SqlDbType.SmallInt).Value = Profile.CurrTemplate;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
//ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + Profile.CurrTemplate + "');</script>", false);
if (Profile.DefaultTemplate != 0)
{
DisplayGridTA.FillBy(DisplayGridDT, DType, (short)tmpid);
}
if (DisplayGridDT.Rows.Count == 0)
{
DisplayGridTA.Fill(DisplayGridDT, getUserID(), DType);
}
StatsFormatGrid.Columns.Clear();
//Stat IsDisplayed
columnchkbx = new GridCheckBoxColumn();
columnchkbx.HeaderText = "Displayed";
columnchkbx.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnchkbx);
//Stats Name
column = new GridBoundColumn();
column.HeaderText = "Stats Name";
column.DataField = DisplayGridDT.Columns[0].ColumnName;
column.UniqueName = DisplayGridDT.Columns[0].ColumnName;
StatsFormatGrid.Columns.Add(column);
//Invisible columns
for (int i = 3; i <= 6; i++)
{
column = new GridBoundColumn();
column.HeaderText = (i == 3) ? "StatsTable.Stats_id" : (i == 4) ? "StatsTable.StatsValue_Type" : (i == 5) ? "StatsTable.Stats_CHeader" : "StatsTable.Stats_Desc";
column.DataField = DisplayGridDT.Columns[i].ColumnName;
column.UniqueName = DisplayGridDT.Columns[i].ColumnName;
column.Visible = false;
StatsFormatGrid.Columns.Add(column);
}
//Dynamically created column - Stats Display Format
columntxtbx = new GridTemplateColumn();
columntxtbx.HeaderText = "Stats Display Format";
columntxtbx.ItemTemplate = new MyTemplate(DisplayGridDT, getUserID(),Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columntxtbx);
/*
columnArrow = new GridTemplateColumn();
columnArrow.ItemTemplate = new ArrowTemplate(DisplayGridDT, getUserID(), Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columnArrow);*/
columnUp = new GridButtonColumn();
columnUp.Text = "↑";
columnUp.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnUp);
columnDown = new GridButtonColumn();
columnDown.Text = "↓";
columnDown.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnDown);
StatsFormatGrid.DataSource = DisplayGridDT;
StatsFormatGrid.DataBind();
foreach (GridDataItem item in StatsFormatGrid.Items) //sets the properties of IsDisplayed
{
DataRowView row = (DataRowView)item.DataItem;
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
chkbx.Enabled = true;
chkbx.AutoPostBack = true;
String value = row["IsDisplayed"].ToString();
chkbx.Checked = (value == "True");
}
}
/// <summary>
/// This is the template for GridTemplateColumn in the display page's grid
/// This represent the column DisplayString
/// Three different kinds of contents are used in each cell of the column depending on StatsValue_Type
/// </summary>
private class MyTemplate : ITemplate
{
//protected RequiredFieldValidator validator1;
//protected RangeValidator validator2;
protected TextBox textBox;
protected DropDownList ddList;
protected Label txtlb;
protected Button up;
protected Button down;
private DisplayGrid.DisplayGridDataTable MyDT = new DisplayGrid.DisplayGridDataTable();
private DisplayGridTableAdapters.DisplayGridTableAdapter MyTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
private Guid myUserID = new Guid();
private int template;
public MyTemplate(DisplayGrid.DisplayGridDataTable DGDT, Guid UserID,int tempid)
{
MyDT = DGDT;
myUserID = UserID;
template = tempid;
}
public void InstantiateIn(System.Web.UI.Control container)
{
//textBox = new TextBox();
ddList = new DropDownList();
txtlb = new Label();
up = new Button();
up.Text = "↑";
down = new Button();
down.Text = "↓";
//textBox.ID = "templateColumnTextBox";
ddList.ID = "templateColumnDDList";
txtlb.ID = "txtLabel";
up.ID = "up";
down.ID = "down";
//textBox.DataBinding += new EventHandler(textBox_DataBinding);
ddList.DataBinding += new EventHandler(ddList_DataBinding);
txtlb.DataBinding += new EventHandler(label_DataBinding);
up.Click += new EventHandler(up_Click);
down.Click += new EventHandler(down_Click);
/*validator1 = new RequiredFieldValidator();
validator1.ControlToValidate = "templateColumnTextBox";
validator1.ErrorMessage = "*";
validator1.Display = ValidatorDisplay.Dynamic;
validator2 = new RangeValidator();
validator2.ControlToValidate = "templateColumnTextBox";
validator2.Type = ValidationDataType.Integer;
validator2.MinimumValue = "0";
validator2.MaximumValue = "12";
validator2.ErrorMessage = "*0-12";
validator2.Display = ValidatorDisplay.Dynamic;*/
//container.Controls.Add(textBox);
container.Controls.Add(ddList);
container.Controls.Add(txtlb);
container.Controls.Add(up);
container.Controls.Add(down);
//container.Controls.Add(validator1);
//container.Controls.Add(validator2);
}
/// <summary>
/// Generates the text boxes when StatsValue_Type is double or percentage
/// Assigns the text and the style
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/*protected void textBox_DataBinding(object sender, EventArgs e)
{
TextBox tBox = (TextBox)sender;
GridDataItem container = (GridDataItem)tBox.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "double" || valType == "percentage")
{
tBox.Text = displayStr.Remove(displayStr.IndexOf(" "));
tBox.Font.Bold = true;
tBox.Style["text-align"] = "center";
tBox.Width = 70;
tBox.AutoPostBack = true;
//tBox.TextChanged += new EventHandler(DisplayTextBox_TextChanged);
}
else
{
tBox.Enabled = false;
tBox.Visible = false;
}
}*/
protected void up_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
GridDataItem container = (GridDataItem)bt.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
int num = Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' ')))+1;
string updateDisplay = num.ToString() + " decimals";
string updateVal = "{0:f" + num.ToString() + "}";
short stats_id = Convert.ToInt16(rdm);
if (num < 13 && num > -1)
{
MyTA.UpdateQuery(updateVal, updateDisplay, stats_id, (short)template);
}
}
protected void down_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
GridDataItem container = (GridDataItem)bt.NamingContainer;
//ScriptManager.RegisterStartupScript(bt, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
int num = Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' '))) -1;
string updateDisplay = num.ToString() + " decimals";
string updateVal = "{0:f" + num.ToString() + "}";
short stats_id = Convert.ToInt16(rdm);
if (num < 13 && num > -1)
{
MyTA.UpdateQuery(updateVal, updateDisplay, stats_id, (short)template);
}
}
/// <summary>
/// Generates the drop down lists when StatsValue_Type is Date
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ddList_DataBinding(object sender, EventArgs e)
{
DropDownList dl = (DropDownList)sender;
GridDataItem container = (GridDataItem)dl.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "Date")
{
dl.Items.Add(new ListItem("MM-DD-YY", "{0:MM-dd-yy}"));
dl.Items.Add(new ListItem("DD-MM-YY", "{0:dd-MM-yy}"));
dl.Items.Add(new ListItem("DD-MMM-YYYY", "{0:dd-MMM-yyyy}"));
dl.SelectedIndex = (displayStr == "MM-DD-YY") ? 0 : (displayStr == "DD-MM-YY") ? 1 : 2;
dl.AutoPostBack = true;
dl.SelectedIndexChanged += new EventHandler(DisplayDDList_IndexChanged);
up.Visible = false;
down.Visible=false;
}
/*else if (valType == "double" || valType == "percentage")
{
dl.Items.Add(new ListItem("1 decimals", "{0:f1}"));
dl.Items.Add(new ListItem("2 decimals", "{0:f2}"));
dl.Items.Add(new ListItem("3 decimals", "{0:f3}"));
dl.Items.Add(new ListItem("4 decimals", "{0:f4}"));
dl.Items.Add(new ListItem("5 decimals", "{0:f5}"));
dl.Items.Add(new ListItem("6 decimals", "{0:f6}"));
dl.Items.Add(new ListItem("7 decimals", "{0:f7}"));
dl.Items.Add(new ListItem("8 decimals", "{0:f8}"));
dl.Items.Add(new ListItem("9 decimals", "{0:f9}"));
dl.Items.Add(new ListItem("10 decimals", "{0:f10}"));
dl.Items.Add(new ListItem("11 decimals", "{0:f11}"));
dl.Items.Add(new ListItem("12 decimals", "{0:f12}"));
dl.SelectedIndex =Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' ')));
dl.AutoPostBack = true;
dl.SelectedIndexChanged += new EventHandler(DisplayDDList_IndexChanged);
}*/
else
{
dl.Enabled = false;
dl.Visible = false;
}
}
/// <summary>
/// Generates the words " digits" after the textboxes when StatsValue_Type is double or percentage
/// Generates the label with text of DisplayString when StatsValue_Type is bit
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void label_DataBinding(object sender, EventArgs e)
{
Label lbl = (Label)sender;
GridDataItem container = (GridDataItem)lbl.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "bit")
{
lbl.Text = displayStr;
lbl.Font.Bold = true;
up.Visible = false;
down.Visible = false;
}
else if (valType == "double" || valType == "percentage") {
lbl.Text = displayStr;
lbl.Font.Bold = true;
}
else { lbl.Text = ""; }
}
/// <summary>
/// Handles the event when textbox is sumbitted
/// inefficient at the moment because it is fired for every textbox every tab change
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/*protected void DisplayTextBox_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
GridDataItem container = (GridDataItem)tb.NamingContainer;
string textCur = ((TextBox)sender).Text + " decimals";
string textOld = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string testing = ((DataRowView)container.DataItem)[MyDT.Columns[0].ColumnName].ToString();
if (textCur != textOld)
{
int value = Convert.ToInt16(((TextBox)sender).Text);
short stats_id = Convert.ToInt16(((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString());
string format = "{0:f" + value.ToString() + "}";
string text = value.ToString() + " decimals";
ScriptManager.RegisterStartupScript(tb, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
//MyTA.UpdateDisplayGrid(format, text, myUserID, stats_id);
MyTA.UpdateQuery(format, text, stats_id, (short)template);
}
}*/
/// <summary>
/// Handles the event when dropdownlist selection changes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DisplayDDList_IndexChanged(object sender, EventArgs e)
{
string date = ((DropDownList)sender).SelectedItem.Text;
string format = ((DropDownList)sender).SelectedItem.Value;
DropDownList ddl = (DropDownList)sender;
GridDataItem container = (GridDataItem)ddl.NamingContainer;
short stats_id = Convert.ToInt16(((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString());
//MyTA.UpdateDisplayGrid(format, date, myUserID, stats_id);
MyTA.UpdateQuery(format, date, stats_id, (short)template);
}
}
//this is called on postback
protected void loadDynamicDisplayGrid(int tmpid)
{
ArrayList oldchkbxList = new ArrayList();
short DType = Convert.ToInt16(displayTabs.SelectedTab.Value);
GridBoundColumn column;
GridColumn columnchkbx;
GridTemplateColumn columntxtbx;
GridButtonColumn columnUp;
GridButtonColumn columnDown;
//GridTemplateColumn columnArrow;
DisplayGrid.DisplayGridDataTable DisplayGridDT = new DisplayGrid.DisplayGridDataTable();
DisplayGridTableAdapters.DisplayGridTableAdapter DisplayGridTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
//update statsformat for the user if necessary
if (Profile.CurrTemplate != 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDB_ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("UpdateNewStat", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#userid", SqlDbType.UniqueIdentifier).Value = getUserID();
command.Parameters.Add("#tempid", SqlDbType.SmallInt).Value = Profile.CurrTemplate;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
if (Profile.DefaultTemplate != 0)
{
DisplayGridTA.FillBy(DisplayGridDT, DType, (short)tmpid);
}
if (DisplayGridDT.Rows.Count == 0)
{
DisplayGridTA.Fill(DisplayGridDT, getUserID(), DType);
}
//save the old values of the IsDisplayed checkboxes before refresh
foreach (GridDataItem item in StatsFormatGrid.Items)
{
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
oldchkbxList.Add(chkbx.Checked);
}
StatsFormatGrid.Columns.Clear();
//Stat IsDisplayed
columnchkbx = new GridCheckBoxColumn();
columnchkbx.HeaderText = "Displayed";
columnchkbx.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnchkbx);
//Stats Name
column = new GridBoundColumn();
column.HeaderText = "Stats Name";
column.DataField = DisplayGridDT.Columns[0].ColumnName;
column.UniqueName = DisplayGridDT.Columns[0].ColumnName;
StatsFormatGrid.Columns.Add(column);
//Invisible columns
for (int i = 3; i <= 6; i++)
{
column = new GridBoundColumn();
column.HeaderText = (i == 3) ? "StatsTable.Stats_id" : (i == 4) ? "StatsTable.StatsValue_Type" : (i == 5) ? "StatsTable.Stats_CHeader" : "StatsTable.Stats_Desc";
column.DataField = DisplayGridDT.Columns[i].ColumnName;
column.UniqueName = DisplayGridDT.Columns[i].ColumnName;
column.Visible = false;
StatsFormatGrid.Columns.Add(column);
}
//Dynamically created column - Stats Display Format
columntxtbx = new GridTemplateColumn();
columntxtbx.HeaderText = "Stats Display Format";
columntxtbx.ItemTemplate = new MyTemplate(DisplayGridDT, getUserID(),Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columntxtbx);
/*
columnArrow = new GridTemplateColumn();
columnArrow.ItemTemplate = new ArrowTemplate(DisplayGridDT, getUserID(), Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columnArrow);*/
columnUp = new GridButtonColumn();
columnUp.Text = "↑";
columnUp.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnUp);
columnDown = new GridButtonColumn();
columnDown.Text = "↓";
columnDown.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnDown);
StatsFormatGrid.DataSource = DisplayGridDT;
StatsFormatGrid.DataBind();
int itr = 0;
foreach (GridDataItem item in StatsFormatGrid.Items) //sets the properties of IsDisplayed
{
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
chkbx.Enabled = true;
chkbx.AutoPostBack = true;
chkbx.Checked = (Boolean)oldchkbxList[itr];
DataRowView row = (DataRowView)item.DataItem;
String value = row["IsDisplayed"].ToString();
if (value == "True" && !(Boolean)oldchkbxList[itr])
{
DisplayedCheckbox_CheckedChanged(chkbx, DisplayGridDT);
}
else if (value != "True" && (Boolean)oldchkbxList[itr])
{
DisplayedCheckbox_CheckedChanged(chkbx, DisplayGridDT);
}
itr++;
}
}
//this is html
<telerik:RadGrid ID="StatsFormatGrid" runat="server" AutoGenerateColumns="False" GridLines="None"
OnDataBound="grid_data_bound" EnableAJAX="true">
<%--ClientSettings>
<Selecting AllowRowSelect="True"></Selecting>
</ClientSettings--%>
</telerik:RadGrid>
I believe you are having a common problem with databinding and the ASP.net Page life cycle. Simply put: you first databind the data and then you change it. The Page_Load event handler binds your data, after that the press of the button is handled and it changes the database. However, the control is already bound to a previous version of the data and displays old information.
You should databind your control AFTER the button press has been handled and the change in the database has been processed. Try putting your databinding code in the Page_PreRender event handler.
You can add
Response.Redirect(Request.RawUrl);
after finish updating database in button click event.
Or call functions that init data in your page. For example
private void Page_Load(...)
{
if(!Page.IsPostBack)
{
InitData();
}
}
private void InitData()
{
//Do init data control in your page
// For exp: binding the grid, combo box....
}
protected void btn_Update_Clicked(...)
{
//1. Update database
//2. Call InitData() function to reload data from database
}
I have created an asp.net usercontrol that should list users in a number of applications. For that purpose, the control renders a repeater (foreach application) which in turn renders a gridview (with users for that application).
The control renders fine, except the fact that columns in the gridview are not sortable. Nothing happens (no postback) when clicking the headers. Apparently, no JavaScript is rendered to perform the postback when clicking the header.
This is the code:
[DefaultProperty("Text")]
[ToolboxData("<{0}:UserList runat=\"server\"></{0}:UserList>")]
public class UserList : WebControl
{
#region Variables
private Repeater list;
private Literal heading;
#endregion
#region Events
#endregion
#region Constructors
public UserList() : base()
{
// Default settings for list control.
list = new Repeater() { ID = "userList" };
heading = new Literal() { ID = "userListHeading" };
}
#endregion
#region Control event handlers
protected override void OnInit(EventArgs e)
{
var css = "<link href=\"" + Page.ClientScript.GetWebResourceUrl(typeof(UserList), "Web.UI.Resources.CSS.UserList.css") + "\" type=\"text/css\" rel=\"stylesheet\" />";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UserListCss", css, false);
base.OnInit(e);
}
public override void RenderControl(HtmlTextWriter writer)
{
heading.RenderControl(writer);
list.RenderControl(writer);
base.RenderControl(writer);
}
protected override void OnLoad(EventArgs e)
{
// set properties
list.ItemTemplate = new ListTemplate();
// attach event handlers
list.ItemDataBound += new RepeaterItemEventHandler(OnList_ItemDataBound);
// bind data
var allRoles = AdvancedRoleProvider.Instance.GetAllRoles();
String appName = (Roles.ApplicationName.Equals("*") ? " alle applikationer" : Roles.ApplicationName);
heading.Text = String.Format("<h2>{0}</h2>", "Brugere i " + appName);
if (allRoles.Count == 0)
{
heading.Text += "Der kunne ikke findes nogen brugere.";
}
else
{
list.DataSource = allRoles;
list.DataBind();
}
base.OnLoad(e);
}
#endregion
#region List control event handlers
protected void OnList_ItemDataBound(Object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
KeyValuePair<String, IList<String>> data = (KeyValuePair<String, IList<String>>)e.Item.DataItem;
Literal litApplication = (Literal)e.Item.FindControl("litApplication");
litApplication.Text = String.Format(litApplication.Text, data.Key);
GridView gvUsers = (GridView)e.Item.FindControl("gvUsers");
gvUsers.RowDataBound += new GridViewRowEventHandler(OnGridViewUsers_RowDataBound);
gvUsers.Sorting += new GridViewSortEventHandler(OnGridViewUsers_Sorting);
gvUsers.DataSource = AdvancedRoleProvider.Instance.GetApplicationUsers(data.Key);
gvUsers.DataBind();
}
}
#endregion
void OnGridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
void OnGridViewUsers_Sorting(object sender, GridViewSortEventArgs e)
{
// TODO: Impl. sorting logic
}
#region List layout template
/// <summary>
/// Layout template class for the repeater control.
/// </summary>
public class ListTemplate : ITemplate
{
#region Constructors
public ListTemplate()
{
}
#endregion
#region Public methods
public void InstantiateIn(Control container)
{
GridView gvUsers;
gvUsers = new GridView() { ID = "gvUsers", AutoGenerateColumns = false, AllowSorting = true };
BoundField userField = new BoundField() { HeaderText = "Bruger", DataField = "UserName", SortExpression = "UserName" };
userField.HeaderStyle.CssClass = userField.ItemStyle.CssClass = "userName";
BoundField fullNameField = new BoundField() { HeaderText = "Navn", DataField = "FullName", SortExpression = "FullName" };
fullNameField.HeaderStyle.CssClass = userField.ItemStyle.CssClass = "userName";
BoundField roleField = new BoundField() { HeaderText = "Rolle", DataField = "RoleName", SortExpression = "RoleName" };
roleField.HeaderStyle.CssClass = roleField.ItemStyle.CssClass = "roleName";
BoundField adField = new BoundField() { HeaderText = "AD Gruppe", DataField = "ADGroupName", SortExpression = "ADGroupName" };
adField.HeaderStyle.CssClass = adField.ItemStyle.CssClass = "adGroupName";
gvUsers.Columns.Add(userField);
gvUsers.Columns.Add(fullNameField);
gvUsers.Columns.Add(roleField);
gvUsers.Columns.Add(adField);
container.Controls.Add(new LiteralControl("<div id=\"userList\">"));
container.Controls.Add(new Literal() { ID = "litApplication", Text="<h3>{0}</h3>" });
container.Controls.Add(gvUsers);
container.Controls.Add(new LiteralControl("</div>"));
}
#endregion
#region Event handlers
#endregion
#region Properties
#endregion
}
#endregion
}
Any help would be greatly appreciated.
I don't know if this will work or not, but you may want try adding the grid through the designer/html. Also, you may want to add the handler at the html side as well instead of the OnList_ItemDataBound. Hope this helps.
<asp:GridView ID="gvUsers" runat="server" AllowSorting="True" onsorting="OnGridViewUsers_Sorting">
How can i remove the tabs from tabcontrol when i reference each tab to the childform.
I am using a tabcontrol, i want to remove a particular tab from the control. The value i have to do this in a string which i dynamically.
How to remove the tab from tabcontrol using a existing tab name which i have in a string ??
I tried something like...
string tabToRemove = "tabPageName";
for (int i = 0; i < myTabControl.TabPages.Count; i++)
{
if (myTabControl.TabPages[i].Name.Equals(tabToRemove, StringComparison.OrdinalIgnoreCase))
{
myTabControl.TabPages.RemoveAt(i);
break;
}
}
But in the above code, the myTabControl.TabPages.Count is always zero.
Below is the code, to show i am creating the tabs. This is working perfectly.
public void TabIt(string strProcessName)
{
this.Show();
//Creating MDI child form and initialize its fields
MDIChild childForm = new MDIChild();
childForm.Text = strProcessName;
childForm.MdiParent = this;
//child Form will now hold a reference value to the tab control
childForm.TabCtrl = tabControl1;
//Add a Tabpage and enables it
TabPage tp = new TabPage();
tp.Parent = tabControl1;
tp.Text = childForm.Text;
tp.Show();
//child Form will now hold a reference value to a tabpage
childForm.TabPag = tp;
//Activate the MDI child form
childForm.Show();
childCount++;
//Activate the newly created Tabpage.
tabControl1.SelectedTab = tp;
tabControl1.ItemSize = new Size(200, 32);
tp.Height = tp.Parent.Height;
tp.Width = tp.Parent.Width;
}
public void GetTabNames()
{
foreach (string strProcessName in Global.TabProcessNames)
{
TabIt(strProcessName);
}
}
The child form :
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Drawing.Drawing2D;
namespace Daemon
{
/// <summary>
/// Summary description for MDIChild.
/// </summary>
///
public class MDIChild : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private TabControl tabCtrl;
private TabPage tabPag;
public MDIChild()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//MDIChild TargerForm = new MDIChild();
//WinApi.SetWinFullScreen(TargerForm.Handle);
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
public TabPage TabPag
{
get
{
return tabPag;
}
set
{
tabPag = value;
}
}
public TabControl TabCtrl
{
set
{
tabCtrl = value;
}
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// MDIChild
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
this.ClientSize = new System.Drawing.Size(0, 0);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MDIChild";
this.Opacity = 0;
this.ShowIcon = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "MDIChild";
this.Activated += new System.EventHandler(this.MDIChild_Activated);
this.Closing += new System.ComponentModel.CancelEventHandler(this.MDIChild_Closing);
this.ResumeLayout(false);
}
#endregion
private void MDIChild_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
//Destroy the corresponding Tabpage when closing MDI child form
this.tabPag.Dispose();
//If no Tabpage left
if (!tabCtrl.HasChildren)
{
tabCtrl.Visible = false;
}
}
catch (Exception ex)
{
}
}
private void MDIChild_Activated(object sender, System.EventArgs e)
{
try
{
//Activate the corresponding Tabpage
tabCtrl.SelectedTab = tabPag;
if (!tabCtrl.Visible)
{
tabCtrl.Visible = true;
}
Global.ExistingTabProcessNames.Add(tabPag.Text);
}
catch (Exception ex)
{
}
}
}
}
For starters you should be looping the other way around:
for (int i = myTabControl.TabPages.Count - 1; i >= 0 ; i--)
{
......
}
EDIT: Ignore me. I missed the break; and yes it should also be >= :(
My next theory is you are missing this line:
// add the page to the tab control
tabControl1.Controls.Add(tp);
PS: Why does copying code from SO not maintain the CRLFs. That is very annoying!
As jussij suggested, you need to do this:
tabControl1.Controls.Add(tp);
And you can more easily locate the tab like this:
var foundTab = (from System.Windows.Forms.TabPage tab in tabControl1.TabPages.Cast<TabPage>()
where tab.Name == "tabName"
select tab).First();
I dont know the purpose of your code, but if you will eventually re-add the tab, why not just hide it? Its easier and you dont have to worry about reverse loop logic and invalid arguments once the page is hidden and such. If you need to need a way to address all the tabs at once just do a check for visible tabs...
I would recommend taking a look at this tab page example for adding/removing tabs.