How to use generated ID's in code behind ASP.NET - c#

I want to hide or show section of my webpage. The problem is that the css Id's are created in the code behind. I do not know how to access them. Any help would be greatly appreciated.
In the fonction ShowColumn KanbanColum should be collapseSection0, collapseSection1 .... And collapseSection collapseDiv0, collapseDiv1 .... but I cant access them. since does variables are created in the background.
protected void ShowColumn(object sender, EventArgs e)
{
kanbanColumn.Visible = true;
collapseSection.Visible = false;
}
public void PopulateLists(int numberOfColumns,List<string> lstColumnsNames, List<int> lstTaskPerColumns, List<string> lstTaskText, List<string> headerColorOptions)
{
HtmlGenericControl li;
string colorChosen;
for (int j = 0; j < numberOfColumns; j++)
{
System.Web.UI.HtmlControls.HtmlGenericControl CollapseDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
CollapseDiv.ID = "collapseSection" + j;
CollapseDiv.Attributes.Add("class", "collapsed-kanban");
CollapseDiv.Style.Add("background-color", "#f4ce46");
dragListColumns.Controls.Add(CollapseDiv);
ImageButton expanImage = new ImageButton();
expanImage.ImageUrl= "~/images/maximize.png";
expanImage.ID = "expandImageId" + j;
expanImage.Height = 20;
expanImage.Width = 20;
expanImage.Attributes.Add("class", "second-menu-icon");
expanImage.Attributes.Add("OnClick", "ShowColumn");
CollapseDiv.Controls.Add(expanImage);
Label lblCollapse = new Label();
lblCollapse.Text = lstColumnsNames[j];
lblCollapse.Attributes.Add("class", "vertical-text");
CollapseDiv.Controls.Add(lblCollapse);
}
}
Here is a image to visual represent the code.
What can I do to be able to use the cssId's that I have created in the background or is there another way to do around the problem. Thank you very much.

Maybe you mean that you find different IDs on the generated web page than the ones you define in codebehind?
You might want to take a look at the ClientIDMode property of asp net tags.
If you don't specify it clearly, ASP.NET generates some weird IDs for your html.
Check THIS article and see if it's what you're looking for.
If you want to manage the ids from the page side, you NEED javascript.
Use JQuery to easily access the ids

Related

Dynamic button-C#

i have buttons this buttons for categories i want when click in this buttons i want to get rows from database products table and get two data product name and price and set it those values into dynamic buttons in windows application notes i have set location properities for button such like flowLayoutPanel
i have this code
private void btnhotdrink_Click_1(object sender, EventArgs e)
{
//int StartPositition = 100;
//int EndPosition = 10;
DataTable dt = new DataTable();
dt =clsprdcat.GET_HOTDRINK_CATEGORY();
for(int i=0; i < dt.Rows.Count; i++)
{
for (int s=0; s < dt.Columns[4]; s++)
{
Button l = addbuttons(i,s);
flowLayoutPanel1.Controls.Add(l);
//EndPosition +=70;
}
}
}
Button addbuttons(int i)
{
Button l = new Button();
l.Name = "Name" + l.ToString();
l.Text = "label" + l.ToString();
l.ForeColor = Color.White;
l.BackColor = Color.Green;
l.Font = new Font("Serif", 24, FontStyle.Bold);
l.Width = 170;
l.Height = 80;
//l.Location = new Point(start, end);
l.TextAlign = ContentAlignment.MiddleCenter;
l.Margin = new Padding(5);
return l;
}
How Can i Do this
All Buttons are inherently dynamically created at runtime. The Windows Forms Designer works via partial classes: You work on one part. The designer on the other (designer.cs). And at compile time the Designers code is executed by calling "InitializeComponents()" in the Constructor. It can only do exactly the same things you can do.
If you need help with creating buttons yourself, you can always look into the Designer part. Just do take care not to change anything in that part. This System only works because the designer is exclusively writing in the file and compilation/loading of a Project is prone to seizing up if you did manual changes.
As you wrote it right now, this code will create dt.Rows.Count buttons at the same locaiton. Usually the Button creation code it needs access to the loop variable, to adapt the positions of each consequtive element.. Personally I prefer to leave positioning of Elements as much to automatics as possible. These designs simply adapt better to changes in resolution and window size.

Dynamic Control automatically removed from PlaceHolder on Button Click

I am adding the dynamically TextBox in the placeholder on the button click in that.
When all the textboxes are loaded I am making changes in the values and again Press another Button to save the values to the SharePoint List. But when I press the Save button and I checked the placeholder by debugging it I found that there were no any control in the placeholder.
I am adding the Controls like follows :
TextBox[] tb = new TextBox[item_ans.Count];
Literal[] lt = new Literal[item_ans.Count];
for (int j = 0; j < item_ans.Count; j++)
{
ans_id.Add(item_ans[j]["ID"].ToString());
tb[j] = new TextBox();
tb[j].ID = "tb_ans" + (j + 1).ToString();
tb[j].Text = item_ans[j]["Title"].ToString();
lt[j] = new Literal();
lt[j].Text = "<br/>";
pl_hd_ans.Controls.Add(tb[j]);
pl_hd_ans.Controls.Add(lt[j]);
}
And on the Save Button click I am Retrieving those TextBoxes Like follows:
int n = Convert.ToInt32(ViewState["totalAns"].ToString());
foreach (var i in ans_id)
{
var item_ans = list_ans.GetItemById(i);
clientContext.Load(item_ans);
clientContext.ExecuteQuery();
for (int k = 0; k < n; k++)
{
TextBox tb = (TextBox)pl_hd_ans.FindControl("tb_ans" + (k + 1).ToString());
item_ans["Title"] = tb.Text;
item_ans.Update();
clientContext.Load(item_ans);
clientContext.ExecuteQuery();
}
}
But in this I check the Placeholder's Controls that were 0. Can Any one please help me to solve this..?
I'm assuming its ASP.NET WebForms what we're talking about here.
When you are adding controls dynamically to the webpage, you have to recreate them on each sequential postback. The reason for this, is that the dynamically created controls are not present in the .aspx file, nor in the viewstate, so asp.net cannot know that it has to recreate these controls. Therefore, you yourself have to recreate them in the initialized-event (before the page-load), including adding any event handlers that you need.
You can google about it.

How to use a Variable or Function to declare my SqlDataSource ID in HTML

I'm writing a for loop that displays a list of links with some chartfx display. The chartfx needs an sqlDataSource. I'm trying to give the unique ID each time the for loop does one iteration but I can not pass it a value or function. Example below in my code.
getSQLID() is just a function that returns a string which I want to be my ID. This is all done on the aspx page and the function is in the .cs . Any help would be really appreciated thank you.
//name of the contentplace holder on the aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server" >
//code behind
Control ctrl = LoadControl("WebUserControl.ascx");
Control placeHolderControl = this.FindControl("Content2");
Control placeHolderControl2 = this.FindControl("ContentPlaceHolder1");
ctrl.ID = "something";
if (placeHolderControl != null)
placeHolderControl.Controls.Add(ctrl);
if (placeHolderControl2 != null)
placeHolderControl2.Controls.Add(ctrl);
First of all, recall that server controls declared in the designer like this are attached to your class at compile time. So it doesn't make sense to try to create multiple instances in a loop at runtime, and that's why the values in e.g. the Id tag have to be known at compile time.
One alternative is to create them in the code behind, with something like:
for (int i=0; i<2; ++i)
{
var chart = new Chart();
chart.Id = "chartId" + i;
chart.DataSourceId = "srcid" + i;
var src = new SqlDataSource();
src.Id = "srcid" + i;
Controls.Add(chart); // either add to the collection or add as a child of a placeholder
Controls.Add(src);
}
In your case converting all of those declarative properties to the code behind can be a bit of work (though it is possible). An alternative is to make a user control (ascx) that contains the markup that's now in your aspx page. You would instantiate the controls in your code behind with something like:
for (int i=0; i<2; ++i)
{
var ctrl = LoadControl("~/path/to/Control.ascx");
ctrl.Id = "something_" + i;
Controls.Add(ctrl); // again, either here or as a child of another control
// make the src, hook them up
}

Custom Header in GridView

I've already got my custom header drawing in my GridView using SetRenderMethodDelegate on the header row within the OnRowCreated method. I'm having problems trying to add LinkButtons to the new header row though.
This is what the RenderMethod looks like:
private void RenderSelectionMode(HtmlTextWriter output, Control container)
{
TableHeaderCell cell = new TableHeaderCell();
cell.Attributes["colspan"] = container.Controls.Count.ToString();
AddSelectionModeContents(cell);
cell.RenderControl(output);
output.WriteEndTag("tr");
HeaderStyle.AddAttributesToRender(output);
output.WriteBeginTag("tr");
for(int i = 0; i < container.Controls.Count; i++)
{
DataControlFieldHeaderCell cell = (DataControlFieldHeaderCell)container.Controls[i];
cell.RenderControl(output);
}
}
private void AddSelectionModeContents(Control parent)
{
// TODO: should add css classes
HtmlGenericControl label = new HtmlGenericControl("label");
label.InnerText = "Select:";
selectNoneLK = new LinkButton();
selectNoneLK.ID = "SelectNoneLK";
selectNoneLK.Text = "None";
//selectNoneLK.Attributes["href"] = Page.ClientScript.GetPostBackClientHyperlink(selectNoneLK, "");
//selectNoneLK.Click += SelectNoneLK_Click;
selectNoneLK.Command += SelectNoneLK_Click;
selectAllLK = new LinkButton();
selectAllLK.ID = "SelectAllLK";
selectAllLK.Text = "All";
//selectAllLK.Attributes["href"] = Page.ClientScript.GetPostBackClientHyperlink(selectAllLK, "");
//selectAllLK.Click += SelectAllLK_Click;
selectAllLK.Command += SelectAllLK_Click;
parent.Controls.Add(label);
parent.Controls.Add(selectNoneLK);
parent.Controls.Add(selectAllLK);
}
As you can see, I have tried different ways to get my LinkButtons working (none have worked though). The LinkButtons are rendered as plain anchor tags, like this: <a id="SelectNoneLK">None</a>
I know there is something wrong with the fact that the ID looks like that, since I am using a Master page for this and the ID should be something much longer.
Any help would be appreciated!
Nick
I'd guess that since cell is not part of the control hierarchy (you never add it to the table), the LinkButton's never find an IContainer parent to rewrite their ID's.
I tend to solve these types of issues using the excellent RenderPipe control that allows me to declare my controls in one place, but render them somewhere else.

Changing a ListBox selection changes other ListBox's selection. What's going on?

I've got a Windows Forms application with two ListBox controls on the same form.
They both have their SelectionMode set to 'MultiExtended'.
When I change the selection of one the selection of the other changes.
Now I thought I'd done something stupid with my SelectedIndexChanged handlers so I removed them and re-wrote them from scratch, and got the problem.
So I created a brand new WinForms app and dragged two ListBoxes onto the forms surface.
In the constructor I populated them both with the following.
List<Thing> data = new List<Thing>();
for ( int i = 0; i < 50; i++ ) {
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data.Add(temp);
}
listBox1.DataSource = data;
listBox1.DisplayMember = "Letters";
listBox1.ValueMember = "Id";
List<Thing> data2 = new List<Thing>();
for ( int i = 0; i < 50; i++ ) {
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data2.Add(temp);
}
listBox2.DataSource = data2;
listBox2.DisplayMember = "Letters";
listBox2.ValueMember = "Id";
And then I built and ran the app.
Started selecting some values to see if the symptoms were present.
And they were!
This is literally all the code I added to the form,I had not added any event handlers, I have tried it with the SelectionMode set to 'One' and 'MultiExtended'.
Can anyone give me a clue as to why this is happening.
Cheers
It isn't the list that stores the current position - it is the CurrencyManager. Any controls (with the same BindingContext) with the same reference as a DataSource will share a CurrencyManager. By using different list instances you get different CurrencyManager instances, and thus separate position.
You could achieve the same simply by using .ToList(), or creating a new List<T> with the same contents (as per your original post), or by assigning a new BindingContext to one of the controls:
control.BindingContext = new BindingContext();
I believe that your two controls are sharing a CurrencyManager. I'm not sure exactly why.
As a workaround, you could try just populating your listboxes with simple strings. Or you may want to try creating separate instances of the BindingSource component, and bind to those.
I experienced the same when I used the same datasource on both listboxes, but creating two equal datasources solved the problem for me. I can see nothing wrong with your code. Anything particular with the Thing class ? Or does it just contain the two members Letters and Id ?
And more...
I finally got ot the bottom of it.
I was binding the two ListBoxes to the same List. by changing the code to
theListBox.DataSource = _contacts.Take(_contacts.Count).ToList();
the issue was curcumvented.
It seems that the reference to the List that it stored also caries any binding or selection information over to the other ListBox.
be careful. ;)
I created a new win forms app with two list boxes on it. They behave as I would expect. Can you post the complete code? Here is my code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private class Thing
{
public String Letters { get; set; }
public Int32 Id { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
List<Thing> data = new List<Thing>();
for (int i = 0; i < 50; i++)
{
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data.Add(temp);
}
listBox1.DataSource = data;
listBox1.DisplayMember = "Letters";
listBox1.ValueMember = "Id";
List<Thing> data2 = new List<Thing>();
for (int i = 0; i < 50; i++)
{
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data2.Add(temp);
}
listBox2.DataSource = data2;
listBox2.DisplayMember = "Letters";
listBox2.ValueMember = "Id";
}
}
I tried to duplicate this behavior on my own machine and was unable to do so running just the code your provided.
I stand corrected.
In another instance of VS in a brand new solution, this works as expected.
God only know's what i've done to make it do what it's doing

Categories