I m adding panel controls in a flowlayoutpanel dynamically as per the number of records in my table. i want to get id from each of the panels so that i can open a popup window on click event of panel. Any sugestions?
here is my code sample.
int id=0;
public void FillSearch()
{
var playerList = dianaDB.TblPlayers.Where(p => p.Status == "Active" & p.CancellationStatus == "Active" & p.Version == "Active").Select(p => p);
Panel pnlPlayer = new Panel();
foreach (var pl in playerList)
{
pnlPlayer = new Panel();
pnlPlayer.Size = new Size(153, 116);
pnlPlayer.BorderStyle = BorderStyle.FixedSingle;
pnlPlayer.Cursor = Cursors.Hand;
pnlPlayer.Click += new EventHandler(pbx_Click);
id=pl.Id;
}
}
private void pbx_Click(object sender, EventArgs e)
{
DlgSearchDetails newDlg = new DlgSearchDetails(id);
newDlg.ShowDialog();
}
You can store the ID of a panel in its Tag property.
pnlPlayer.Tag = id;
Then retrieve it later
private void pbx_Click(object sender, EventArgs e)
{
Panel p = sender as Panel;
if(p != null)
{
//TODO add error handling to ensure Tag contains an int
//...
DlgSearchDetails newDlg = new DlgSearchDetails((int)p.Tag);
newDlg.ShowDialog();
}
}
Assuming , you are asking about the WinForm
There is a tag property in each controls , ypou can utilize it.
public void FillSearch()
{
var playerList = dianaDB.TblPlayers.Where(p => p.Status == "Active" & p.CancellationStatus == "Active" & p.Version == "Active").Select(p => p);
Panel pnlPlayer = new Panel();
foreach (var pl in playerList)
{
pnlPlayer = new Panel();
pnlPlayer.Size = new Size(153, 116);
pnlPlayer.BorderStyle = BorderStyle.FixedSingle;
pnlPlayer.Cursor = Cursors.Hand;
pnlPlayer.Click += new EventHandler(pbx_Click);
pnlPlayer.Tag = pl.Id;
}
}
private void pbx_Click(object sender, EventArgs e)
{
var panle = sender as Panel;
if(panel!=null)
{
DlgSearchDetails newDlg = new DlgSearchDetails(panel.Tag);
newDlg.ShowDialog();
}
}
Related
This is a C# web form project I am starting with after a long time away from IDE coding...
I am trying to make a simple custom dialog box class. This is my code.
public static class Dialogo
{
public static int show ()
{
Form dialogo = new Form();
dialogo.Width = 300;
dialogo.Height = 300;
Button btnSim = new Button() { Text = "Sim", Left = 30, Width = 100 };
Button btnNao = new Button() { Text = "Não", Left = 150, Width = 100 };
dialogo.Controls.Add(btnSim);
dialogo.Controls.Add(btnNao);
dialogo.ShowDialog();
// the following two lines are the problematic ones
btnSim += new EventHandler(btnSim_Click);
btnNao += new EventHandler(btnNao_Click);
return -1;
}
}
It's underlining the text within parenthesis and the message says:
The name btnSim_Click' does not exist in the current context
The problem is that I tried to add the following in my code but it doesn't let me put it anywhere (it always says that is something wrong):
private int btnNao_Click (object sender, EventArgs e)
{
return 0;
}
private int btnSim_Click (object sender, EventArgs e)
{
return 1;
}
My objective is that each of the both buttons btnSim and btnNao return a different value (say 1 and 0).
What am I doing wrong?
EventHandler is a delegate for a method that returns void.
Your methods return int.
Try something like this:
public static int show()
{
int returnValue = -1;
using (Form dialogo = new Form())
{
dialogo.Width = 300;
dialogo.Height = 300;
Button btnSim = new Button() { Text = "Sim", Left = 30, Width = 100 };
Button btnNao = new Button() { Text = "Não", Left = 150, Width = 100 };
dialogo.Controls.Add(btnSim);
dialogo.Controls.Add(btnNao);
btnSim.Click += (s, e) => { returnValue = 0; dialogo.DialogResult = DialogResult.OK; };
btnNao.Click += (s, e) => { returnValue = 1; dialogo.DialogResult = DialogResult.OK; };
dialogo.Disposed += (s, e) =>
{
btnSim?.Dispose();
btnSim = null;
btnNao?.Dispose();
btnNao = null;
};
dialogo.ShowDialog();
}
return returnValue;
}
I have created a small kitchen display program that display food orders. So I created dynamically a panel that contains a table layout panel that contains a checked list box and a check all button . My problem is... I have a check all button in each table layout panel created dynamically and every time I click it, it checks all items in the last created CheckedListBox not the clicked one.
This is my code:
p = new Panel();
p.Size = new System.Drawing.Size(360, 500);
p.BorderStyle = BorderStyle.FixedSingle;
p.Name = "panel";
tpanel = new TableLayoutPanel();
tpanel.Name = "tablepanel";
clb = new CheckedListBox();
tpanel.Controls.Add(b1 = new Button() { Text = "CheckAll" }, 1, 4);
b1.Name = "b1";
b1.Click += new EventHandler(CheckAll_Click);
b1.AutoSize = true;
private void CheckAll_Click(object sender, EventArgs e)
{
var buttonClicked = (Button)sender;
var c = GetAll(this, typeof(CheckedListBox));
for (int i = 0; i < c.Count(); i++)
{
\\any help
}
}
public IEnumerable<Control> GetAll(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl, type)).Concat(controls).Where(c =>
c.GetType() == type);
}
First I will describe the struct
Order = TableLayoutPanel
TableLayoutPanel has 1 CheckAll Button and CheckListBox
And you want when you click to CheckAll Button it will checks exactly all items in current TableLayoutPanel.
So try this code
class XForm : Form {
// create Dictionary to store Button and CheckListBox
IDictionary<Button, CheckListBox> map = new Dictionary<Button, CheckListBox> ();
// when you create new order (new TableLayoutPanel)
// just add map Button and CheckListBox to map
private void CreateOrder () {
var panel = new Panel ();
panel.Size = new System.Drawing.Size (360, 500);
panel.BorderStyle = BorderStyle.FixedSingle;
panel.Name = "panel";
var table = new TableLayoutPanel ();
var checklistBox = new CheckedListBox ();
var button = new Button () { Text = "CheckAll" };
table.Controls.Add (button, 1, 4);
button.Name = "b1";
button.Click += new EventHandler (CheckAll_Click);
button.AutoSize = true;
map[button] = checklistBox;
}
// and on event handle
private void CheckAll_Click (object sender, EventArgs e) {
var buttonClicked = (Button) sender;
var c = map[buttonClicked];
if (c == null) return;
for (int i = 0; i < c.Items.Count; i++)
{
c.SetItemChecked(i, true);
}
}
}
And dont for get remove it from map when remove the order.
Hope it helps
Background
I create a set of linklabel and label controls using a loop that uses data from a database as there content (Text).
Question
How do I then remove or change there visibility?
What I would Like to Happen?
On a button click event, I would like all of the link's and linklabel's text properties to be set to either null, or their visibility properties to be set as false.
Code
private void getInfoStationID()
{
//SQL Connection Stuff
for (int i = 0; i <= rowCount - 1; i++)
{
LinkLabel Linklabel = new LinkLabel();
Linklabel.Text = ds.Tables[0].Rows[i] ["code"].ToString();
Linklabel.Height = 15;
Linklabel.Width = 50;
Linklabel.AutoSize = true;
Linklabel.Location = new Point(10, (i + 1) * 30);
tabControl1.TabPages[0].Controls.Add(Linklabel);
// Add an event handler to do something when the links are clicked.
Linklabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
Label label1 = new Label();
label1.Text = ds.Tables[0].Rows[i]["name"].ToString();
label1.Height = 15;
label1.Width = 70;
label1.Location = new Point(100, (i + 1) * 30);
tabControl1.TabPages[0].Controls.Add(label1);
Label label3 = new Label();
label3.Text = ds.Tables[0].Rows[i]["toc"].ToString();
label3.Height = 15;
label3.Width = 50;
label3.Location = new Point(240, (i + 1) * 30);
tabControl1.TabPages[0].Controls.Add(label3);
}
}
private void clearAllBtn_Click(object sender, EventArgs e)
{
//Would like this to clear all previously drawn labels and linklabels
}
Simply add the dynamic controls to a List so you have a quick reference to them:
// out at CLASS/FORM level:
private List<Control> MyControls = new List<Control>();
// ... some method ...
for (int i = 0; i <= rowCount - 1; i++)
{
LinkLabel Linklabel = new LinkLabel();
MyControls.Add(Linklabel);
// ... rest of your code ...
Label label1 = new Label();
MyControls.Add(label1);
// ... rest of your code ...
Label label3 = new Label();
MyControls.Add(label3);
// ... rest of your code ...
}
Now you can use that List from somewhere else:
private void clearAllBtn_Click(object sender, EventArgs e)
{
foreach(Control ctl in MyControls)
{
ctl.Visible = false; // or something else
}
}
*Don't forget to dispose of those controls and empty the list if you decide to create a new set of dynamic controls. If you want to completely get rid of them:
private void clearAllBtn_Click(object sender, EventArgs e)
{
foreach(Control ctl in MyControls)
{
ctl.Dispose();
}
MyControls.Clear();
}
You can loop through all controls on a certain tabpage. You could use a open generic function to make the code nice and clean. Like this:
private void HideControls<TControl>(Control parentControl)
where TControl : Control
{
var controls = parentControl.Controls.OfType<TControl>();
foreach (var control in controls)
{
control.Visible = false;
}
}
And use it like this:
private void button1_Click(object sender, EventArgs e)
{
this.HideControls<Label>(tabControl1.TabPages[0]);
this.HideControls<LinkLabel>(tabControl1.TabPages[0]);
}
You could even refactor this to a nice extension method:
public static class ControlExtensions
{
public static void HideControlsOfType<TControl>(this Control parentControl)
where TControl : Control
{
var controls = parentControl.Controls.OfType<TControl>();
foreach (var control in controls)
{
control.Visible = false;
}
}
}
and use like:
this.tabControl1.TabPages[0].HideControlsOfType<Label>();
I have an asp.net web page that contain panel that will filled up on run time
protected void Page_Load(object sender, EventArgs e)
{
buildStructure(1);
}
and this is the method
public void buildStructure(int level_id)
{
pMain.Controls.Clear();
//Response.Write(#"<script language='javascript'>alert('" + level_id + "');</script>");
DataUtility DU = new DataUtility(#"****");
DataTable dt = DU.GetDataTable("SELECT * FROM dbo.PRStructure_Main WHERE level_id = "+level_id);
int curr_level = 1;
int curr_child = 1;
int totalchild = 0;
if (dt.Rows.Count > 0)
{
Panel pLevel = new Panel();
pLevel.CssClass = "level";
Panel pItem = new Panel();
pItem.CssClass = "item-ceo";
Label lItem = new Label();
lItem.Text = dt.Rows[0].ItemArray[2].ToString();
pItem.Controls.Add(lItem);
pLevel.Controls.Add(pItem);
pMain.Controls.Add(pLevel);
Panel pLevelLine = new Panel();
pLevelLine.CssClass = "level";
Panel pItemLine = new Panel();
pItemLine.CssClass = "item-line-ceo";
Panel pLine = new Panel();
pLine.CssClass = "horizontal-line";
pItemLine.Controls.Add(pLine);
pLevelLine.Controls.Add(pItemLine);
pMain.Controls.Add(pLevelLine);
Panel pLevelLine2 = new Panel();
pLevelLine2.CssClass = "level";
Panel pLevel2 = new Panel();
pLevel2.CssClass = "level";
dt = DU.GetDataTable("SELECT * FROM dbo.PRStructure_Main WHERE level_parent = "+(Convert.ToInt32( dt.Rows[0].ItemArray[0].ToString())));
lbItem2 = new LinkButton[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
Panel pItemLine2 = new Panel();
Panel pLine2 = new Panel();
if (i == 0)
{
pItemLine2.CssClass = "item-line-level2-first";
pLine2.CssClass = "horizontal-line2-first";
}
else if (i == dt.Rows.Count - 1)
{
pItemLine2.CssClass = "item-line-level2-last";
pLine2.CssClass = "horizontal-line2-last";
}
else
{
pItemLine2.CssClass = "item-line-level2-middle";
pLine2.CssClass = "horizontal-line2-middle";
}
pItemLine2.Controls.Add(pLine2);
pLevelLine2.Controls.Add(pItemLine2);
Panel pItem2 = new Panel();
pItem2.CssClass = "item-level2";
Panel pItemContent2 = new Panel();
pItemContent2.CssClass = "item-level2-content";
lbItem2[i] = new LinkButton();
lbItem2[i].Text = dt.Rows[i].ItemArray[2].ToString();
int current_level1 = (int)dt.Rows[i].ItemArray[0];
//lbItem2.OnClientClick = "alert('" + current_level1 + "')";
//lbItem2.Click += new EventHandler((s,e) => evHandler(s,e, current_level1));
lbItem2[i].Click += new System.EventHandler(delegate(Object o, EventArgs a)
{
evHandler(o, a, current_level1);
});
pItemContent2.Controls.Add(lbItem2[i]);
//pLevel.Controls.Add(lbItem);
DataTable dt2 = DU.GetDataTable("SELECT * FROM dbo.PRStructure_Main WHERE level_parent = " + dt.Rows[i].ItemArray[0]);
Panel pMenuLevel = new Panel();
pMenuLevel.CssClass = "menu-level2";
//<div class="menu-level2-items">Assets Integrity Management</div>
for (int j = 0; j < dt2.Rows.Count; j++)
{
Panel pMenuLevelItems = new Panel();
pMenuLevelItems.CssClass = "menu-level2-items";
LinkButton lbMenuItem = new LinkButton();
lbMenuItem.Text = dt2.Rows[j].ItemArray[2].ToString();
int current_level2 = (int)dt2.Rows[j].ItemArray[0];
//lbMenuItem.Click += new EventHandler(delegate (Object o, EventArgs ee) { evHandler(s, ee,current_level2)});
lbMenuItem.Click += new EventHandler(delegate (Object o, EventArgs a)
{
evHandler(o, a, current_level2);
});
pMenuLevelItems.Controls.Add(lbMenuItem);
DataTable dt3 = DU.GetDataTable("SELECT * FROM dbo.PRStructure_Main WHERE level_parent = " + dt2.Rows[j].ItemArray[0]);
Panel pSubMenuLevel = new Panel();
pSubMenuLevel.CssClass = "sub-menu-level2";
// <div class="sub-menu-level2-items"> Business Application Section </div>
for (int k = 0; k < dt3.Rows.Count; k++)
{
Panel pSubMenuLevelItems = new Panel();
pSubMenuLevelItems.CssClass = "menu-level2-items";
LinkButton lbSubMenuItem = new LinkButton();
lbSubMenuItem.Text = dt3.Rows[k].ItemArray[2].ToString();
int current_level3 = (int)dt3.Rows[k].ItemArray[0];
lbMenuItem.Click += new EventHandler((s, e) => evHandler(s, e, current_level3));
pSubMenuLevelItems.Controls.Add(lbSubMenuItem);
pSubMenuLevel.Controls.Add(pSubMenuLevelItems);
}
pMenuLevelItems.Controls.Add(pSubMenuLevel);
pMenuLevel.Controls.Add(pMenuLevelItems);
}
pItemContent2.Controls.Add(pMenuLevel);
pItem2.Controls.Add(pItemContent2);
pLevel2.Controls.Add(pItem2);
}
pMain.Controls.Add(pLevelLine2);
pMain.Controls.Add(pLevel2);
}
}
I have a problem in this section
lbMenuItem.Click += new EventHandler((s, e) => evHandler(s, e, current_level3));
and this is the handler method
public void evHandler(Object s,EventArgs e, int someData){
//Response.Write(#"<script language='javascript'>alert('" + someData + "');</script>");
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),"err_msg","alert('" + someData + "');",
true);
buildStructure(someData);
}
it work properly first time
but when i click it again its make page load.
I think your page_load should be like below
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack){
buildStructure(1);
}
}
You need to recreate the exact same controls when posting back. If the page loads with only one control how will it know to raise the click event for a control that doesn't exists.
Edit:
From what I understand about asp.net page life cycle, you must have the controls created before post back data is restored, that's how page control events fire. So if you have a control say LinkButtonA which was dynamically created on the page and you click on it, for the click event to trigger on the server during the post back, it must be recreated before post back data is restored, therefore try Recreating dynamic controls in Page_Init instead of Page_Load and try to keep the input to your method "buildStructure" the same. Say if you have called it from the event handler with buildStructure("fifth_level") make sure that Page_Init does the same buildStructure("fifth_level").
Microsoft recommends to create the dynamic controls on preint so you need to create the same controls on preinit like this
http://msdn.microsoft.com/en-us/library/ms178472.aspx
protected override void OnPreInit(EventArgs e)
{
}
I am Silverlight developer and coding in C# to select an item from a list and display the selected item in the textBlock nearby.
My code to do so is:
ListBox lines = new ListBox();
TextBlock txtblkShowSelectedValue = new TextBlock();
ScrollViewer scrollViewer = new ScrollViewer();
scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
lines.ItemsSource = param.Component.Attributes.Items;
Grid.SetColumn(lines, 1);
Grid.SetRow(lines, LoopCount);
childGrid.Children.Add(lines);
lines.SelectedIndex = 0;
lines.SelectedItem = param.Component.Attributes.Items;
The problem is how to select a value and how to display it in textblock "txtblkShowSelectedValue " ? because I cannot declare textblock and List variable globally because of current condition if I use selectionChange event
EDIT: The current scenario is :(lines (List) is in different function so it's not in scope of List_SelectionChanged() function)
private static Grid GenerateList(Parameter param, int LoopCount, Grid g)
{
Grid childGrid = new Grid();
ColumnDefinition colDef1 = new ColumnDefinition();
ColumnDefinition colDef2 = new ColumnDefinition();
ColumnDefinition colDef3 = new ColumnDefinition();
childGrid.ColumnDefinitions.Add(colDef1);
childGrid.ColumnDefinitions.Add(colDef2);
childGrid.ColumnDefinitions.Add(colDef3);
TextBlock txtblk1ShowStatus = new TextBlock();
TextBlock txtblkLabel = new TextBlock();
ListBox lines = new ListBox();
ScrollViewer scrollViewer = new ScrollViewer();
scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
lines.ItemsSource = param.Component.Attributes.Items;
Grid.SetColumn(lines, 1);
Grid.SetRow(lines, LoopCount);
childGrid.Children.Add(lines);
lines.SelectedIndex = 0;
lines.SelectedItem = param.Component.Attributes.Items;
lines.SelectionChanged += new SelectionChangedEventHandler(List_SelectionChanged);
lines.SelectedIndex = lines.Items.Count - 1;
g.Children.Add(childGrid);
return (g);
}
static void List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show("clist _SelectionChanged1");
TextBlock txtblk1ShowStatus = new TextBlock();
txtblk1ShowStatus.Text = lines[(sender as ListBox).SelectedIndex];
}
This could be streamlined, but should work as a quick 'n dirty example of one way to solve the problem...
void lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Grid g = null;
ListBox lb = sender as ListBox;
if (lb != null && lb.SelectedIndex >= 0)
{
// Find the top-level grid
var parent = VisualTreeHelper.GetParent(lb);
while (parent != null)
{
if (parent.GetType() == typeof(Grid))
{
if ((parent as Grid).Name.Equals("LayoutRoot"))
{
g = (Grid)parent;
break;
}
}
parent = VisualTreeHelper.GetParent(parent);
}
// Found the LayoutRoot, find the textblock
if (g != null)
{
for (int i = 0; i < g.Children.Count; i++)
{
var child = VisualTreeHelper.GetChild(g, i);
if (child is TextBlock)
{
(child as TextBlock).Text = (string)lb.SelectedItem;
break;
}
}
}
}
}
You could also name your textblock and search for that (as I did for "LayoutRoot").
Obviously, this code assumes the textblock is a child of the top-level Grid. Implementing a recursive search wouldn't be difficult.
lines.SelectionChanged+=new System.EventHandler(this.UpdateTextBlock); // add selectionchanged even for your listbox;
private void UpdateTextBlock(object sender, SelectionChangedEventArgs e)
{
txtblkShowSelectedValue.Text=this.lines[(sender as Listbox).SelectedIndex].ToString(); // just edit the content of your texblock
}
EDIT : thank you, and sorry to be late :-)
try this :
add parameter for the function, as this :
lines.SelectionChanged += new SelectionChangedEventHandler(List_SelectionChanged)
change parameter of this function and set your textblock as this :
static void List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show("clist _SelectionChanged1");
txtblkShowSelectedValue.Text=this.lines[(sender as Listbox).SelectedIndex].ToString()
}
Afteralli solved the problem like this:
lines.SelectionChanged += (o, e) =>
{
MessageBox.Show("clist _SelectionChanged1");
txtblk1ShowStatus.Text = lines.SelectedItem.ToString();
};
lines.SelectedIndex = lines.Items.Count - 1;
in my function GenerateList(..)