Adding Events to MenuItem Dyanamically in C# - c#

I have created menu dynamically.But I don't know how to handle events of menu Item.Please Let me know if anyone have solution.Thanks in Advance.
ToolStripMenuItem master,transaction,report,exit;
private void Menu1_Load(object sender, EventArgs e)
{
master = new ToolStripMenuItem("Master");
menuStrip1.Items.Add(master);
master.DropDownItems.Add("Party Master");
master.DropDownItems.Add("Item Master");
master.DropDownItems.Add("Tax Master");
master.Click += MenuClicked;
transaction = new ToolStripMenuItem("Transaction");
menuStrip1.Items.Add(transaction);
transaction.DropDownItems.Add("Inward");
transaction.DropDownItems.Add("Inoice");
transaction.DropDownItems.Add("Daily Expense");
report = new ToolStripMenuItem("Report");
menuStrip1.Items.Add(report);
report.DropDownItems.Add("Master Report");
report.DropDownItems.Add("Transaction Report");
report.DropDownItems.Add("Daily Expense Report");
exit = new ToolStripMenuItem("Exit");
menuStrip1.Items.Add(exit);
}
private void MenuClicked(object o,EventArgs e)
{
if ((((ToolStripMenuItem)o).Text) == "Party Master")
{
Master.PartyMaster p = new Master.PartyMaster();
p.Show();
}
}`

`// Master
master.DropDownItems.
AddRange(new System.Windows.Forms.ToolStripItem[]
{
partyMaster,
itemMaster,
taxMaster
}
);
master.Name = "Master";
master.Size = new System.Drawing.Size(125, 20);
master.Text = "Master";
master.Click += new System.EventHandler(master_Click);
// Party Master
partyMaster.Name = "PartyMaster";
partyMaster.Size = new System.Drawing.Size(152, 22);
partyMaster.Text = "PartyMaster";
partyMaster.Click += new System.EventHandler(partyMaster_Click);
// Item Master
itemMaster.Name = "ItemMaster";
itemMaster.Size = new System.Drawing.Size(152, 22);
itemMaster.Text = "ItemMaster";
// Tax Master
taxMaster.Name = "TaxMaster";
taxMaster.Size = new System.Drawing.Size(152, 22);
taxMaster.Text = "TaxMaster"; //`
Or more dynamically with List and for loop.
List<ToolStripMenuItem> items = new List<ToolStripMenuItems>();
And loop to add more items to the Menu
ToolStripMenuItem item = new ToolStripMenuItem();
items.Add(item);
item.Click += new EventHandler(MenuClicked); // if you want to stick with only one function

Try add your dropdown items this way:
ToolStripItem partyMaster = new ToolStripMenuItem() { Text = "Party Master" };
partyMaster.Click += MenuClicked;
ToolStripItem itemMaster = new ToolStripMenuItem() { Text = "Item Master" };
itemMaster.Click += MenuClicked;
ToolStripItem taxMaster = new ToolStripMenuItem() { Text = "Tax Master" };
taxMaster.Click += MenuClicked;
master.DropDownItems.Add(partyMaster);
master.DropDownItems.Add(itemMaster);
master.DropDownItems.Add(taxMaster);

Related

DataGridView CheckBox selection bug

Our app has a list of items displayed in a DataGridView. The first column is a DataGridViewCheckBoxColumn. We want our app to allow the user to click anywhere on the row as a way to select the CheckBox in the first column.
We find that if the user clicks directly on the CheckBox, selection/deselection works well. The same is true if the user clicks on the data in the other columns.
However, if the user clicks just to one side of the checkbox, we get strange behavior. The CheckBox in that row is not selected/deselected, but often another row is selected. To get a clearer picture of what is happening, you can check out my Short Video of the buggy behavior.
I tried setting some breakpoints in the code, for example, on our SelectionChanged handler, our CellClick handler and our CellValueChanged handler. I find these breakpoints are hit in the same pattern, regardless of whether I click on the CheckBox, just to one side of the checkbox or on the data in the other columns.
Has anyone seen behavior like this? Any ideas what may be going on? Is it a bug in the .NET DataGridView code, or is there something I should look for in our code?
Here is the relevant code, as requested (or you can download a ZIP file with the complete solution)...
From Form1.cs:
public Form1()
{
InitializeComponent();
dgsControl.SetUp();
}
From Form1.Designer.cs:
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.dgsControl = new DGSelection();
this.Controls.Add(this.dgsControl);
//
// dgsControl
//
this.dgsControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.dgsControl.Location = new System.Drawing.Point(3, 3);
this.dgsControl.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.dgsControl.Name = "dgsControl";
this.dgsControl.Size = new System.Drawing.Size(689, 325);
this.dgsControl.TabIndex = 0;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "DataGridView Demo";
}
From DGSelection.cs:
public partial class DGSelection : UserControl
{
#region Member variables
private class ListData
{
public string Option;
public string Description;
}
private static readonly List<ListData> TestData = new List<ListData>
{
new ListData { Option = "Option1", Description = "Description1" },
new ListData { Option = "Option2", Description = "Description2" },
new ListData { Option = "Option3", Description = "Description3" },
new ListData { Option = "Option4", Description = "Description4" }
};
public event EventHandler OptionsChanged;
#endregion
#region Constructor
public DGSelection()
{
InitializeComponent();
dgvTable.BackgroundColor = Color.DarkGray;
dgvTable.DefaultCellStyle.BackColor = Color.DarkGray;
dgvTable.DefaultCellStyle.ForeColor = Color.Black;
dgvTable.ColumnHeadersDefaultCellStyle.BackColor = Color.DarkGray;
dgvTable.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black;
dgvTable.GridColor = Color.DarkGray;
cbxCheckAll.BackColor = Color.DarkGray;
// Move label where it belongs (moved elsewhere in Designer for ease of editing).
lbl_empty.Top = Top + 5;
}
#endregion
#region Public Methods
public void SetUp()
{
dgvTable.Rows.Clear();
cbxCheckAll.Checked = false;
bool anyRows = TestData.Any();
lbl_empty.Visible = !anyRows;
cbxCheckAll.Visible = anyRows;
dgvTable.ColumnHeadersVisible = anyRows;
foreach (ListData ld in TestData)
{
dgvTable.Rows.Add(false, ld.Option, ld.Description);
}
}
#endregion
#region Event Handlers
private void DGSelection_SelectionChanged(object sender, EventArgs e)
{
dgvTable.ClearSelection();
}
private void cbxCheckAll_CheckedChanged(object sender, EventArgs e)
{
try
{
dgvTable.CellValueChanged -= DgvTableCellValueChanged;
bool checkAll = cbxCheckAll.Checked;
foreach (DataGridViewRow row in dgvTable.Rows)
row.Cells[0].Value = checkAll;
}
finally
{
dgvTable.CellValueChanged += DgvTableCellValueChanged;
}
OptionsChanged?.Invoke(this, EventArgs.Empty);
}
private void DGSelection_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0)
return; // Ignore clicks in the header row
DataGridViewCell checkBoxCell = dgvTable.Rows[e.RowIndex].Cells[0];
checkBoxCell.Value = !(bool)checkBoxCell.Value;
}
private void DgvTableCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
cbxCheckAll.CheckedChanged -= cbxCheckAll_CheckedChanged;
cbxCheckAll.CheckedChanged -= cbxCheckAll_CheckedChanged;
// Not sure why, but sometimes subscribed twice
bool checkAll = dgvTable.Rows.Count > 0;
foreach (DataGridViewRow row in dgvTable.Rows)
checkAll &= row.Cells[0].Value.Equals(true);
cbxCheckAll.Checked = checkAll;
}
finally
{
cbxCheckAll.CheckedChanged += cbxCheckAll_CheckedChanged;
}
OptionsChanged?.Invoke(this, EventArgs.Empty);
}
private void DGSelection_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
dgvTable.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
#endregion
}
From DGSelection.Designer.cs:
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this.dgvTable = new System.Windows.Forms.DataGridView();
this.colCheckboxes = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.colText1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colText2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.cbxCheckAll = new System.Windows.Forms.CheckBox();
this.lbl_empty = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dgvTable)).BeginInit();
this.SuspendLayout();
//
// dgvTable
//
this.dgvTable.AllowUserToAddRows = false;
this.dgvTable.AllowUserToDeleteRows = false;
this.dgvTable.AllowUserToResizeColumns = false;
this.dgvTable.AllowUserToResizeRows = false;
this.dgvTable.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
this.dgvTable.BackgroundColor = System.Drawing.SystemColors.Window;
this.dgvTable.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.dgvTable.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dgvTable.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.ControlDark;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.Padding = new System.Windows.Forms.Padding(3);
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvTable.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dgvTable.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvTable.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colCheckboxes,
this.colText1,
this.colText2 });
this.dgvTable.Dock = System.Windows.Forms.DockStyle.Fill;
this.dgvTable.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter;
this.dgvTable.EnableHeadersVisualStyles = false;
this.dgvTable.Location = new System.Drawing.Point(0, 0);
this.dgvTable.Margin = new System.Windows.Forms.Padding(2);
this.dgvTable.MultiSelect = false;
this.dgvTable.Name = "dgvTable";
this.dgvTable.RowHeadersVisible = false;
this.dgvTable.RowTemplate.Height = 24;
this.dgvTable.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.dgvTable.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
this.dgvTable.Size = new System.Drawing.Size(484, 318);
this.dgvTable.TabIndex = 0;
this.dgvTable.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DGSelection_CellClick);
this.dgvTable.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.DgvTableCellValueChanged);
this.dgvTable.CurrentCellDirtyStateChanged += new System.EventHandler(this.DGSelection_CurrentCellDirtyStateChanged);
this.dgvTable.SelectionChanged += new System.EventHandler(this.DGSelection_SelectionChanged);
//
// colCheckboxes
//
this.colCheckboxes.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
this.colCheckboxes.Frozen = true;
this.colCheckboxes.HeaderText = "";
this.colCheckboxes.Name = "colCheckboxes";
this.colCheckboxes.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.colCheckboxes.Width = 30;
//
// colText1
//
this.colText1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle2.Padding = new System.Windows.Forms.Padding(5, 0, 0, 0);
this.colText1.DefaultCellStyle = dataGridViewCellStyle2;
this.colText1.HeaderText = "Option";
this.colText1.Name = "colText1";
this.colText1.ReadOnly = true;
this.colText1.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.colText1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.colText1.Width = 57;
//
// colText2
//
this.colText2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
dataGridViewCellStyle3.Padding = new System.Windows.Forms.Padding(5, 0, 0, 0);
this.colText2.DefaultCellStyle = dataGridViewCellStyle3;
this.colText2.HeaderText = "Description";
this.colText2.Name = "colText2";
this.colText2.ReadOnly = true;
this.colText2.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.colText2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// cbxCheckAll
//
this.cbxCheckAll.AutoSize = true;
this.cbxCheckAll.BackColor = System.Drawing.SystemColors.ControlDark;
this.cbxCheckAll.Location = new System.Drawing.Point(8, 5);
this.cbxCheckAll.Margin = new System.Windows.Forms.Padding(2);
this.cbxCheckAll.Name = "cbxCheckAll";
this.cbxCheckAll.Size = new System.Drawing.Size(15, 14);
this.cbxCheckAll.TabIndex = 1;
this.cbxCheckAll.UseVisualStyleBackColor = false;
this.cbxCheckAll.CheckedChanged += new System.EventHandler(this.cbxCheckAll_CheckedChanged);
//
// lbl_empty
//
this.lbl_empty.Anchor = ((System.Windows.Forms.AnchorStyles)
(((System.Windows.Forms.AnchorStyles.Top |
System.Windows.Forms.AnchorStyles.Left) |
System.Windows.Forms.AnchorStyles.Right)));
this.lbl_empty.BackColor = System.Drawing.Color.Transparent;
this.lbl_empty.Location = new System.Drawing.Point(3, 25);
this.lbl_empty.Name = "lbl_empty";
this.lbl_empty.Size = new System.Drawing.Size(478, 44);
this.lbl_empty.TabIndex = 2;
this.lbl_empty.Text = "No data defined for the list";
this.lbl_empty.Visible = false;
//
// DGSelection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.lbl_empty);
this.Controls.Add(this.cbxCheckAll);
this.Controls.Add(this.dgvTable);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "DGSelectionControl";
this.Size = new System.Drawing.Size(484, 318);
((System.ComponentModel.ISupportInitialize)(this.dgvTable)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
Is there something in our code which is causing this behavior? Or is it a bug in the implementation of DataGridView? I have reproduced this with both .NET Framework v.4.6 & v.4.8.
(Note: reposted from Microsoft Q&A Forum, since I got no responses there.)
I suggest these changes (tested with .Net Framework 4.8):
Don't use the CheckBox CheckedChanged event: it will interfere with the CellValueChanged event when it tries to change the Select All CheckBox state. Use the CellClick event instead.
This will also allow to get rid of all those add handler / remove handler things.
Call RefreshEdit() to update the state of the CheckBox Cell as soon as the Cell is clicked: this will update the CheckBox value immediately (this is the problem you're seeing when clicking inside the Cell's area instead of the CheckBox content: the control is not updated right away).
For more details, see the notes here:
Programmatically check a DataGridView CheckBox that was just unchecked
Remove that CommitEdit(DataGridViewDataErrorContexts.Commit);: if you need to update a value immediately, call the DataGridView.EndEdit() method instead (see those notes on this, too). It's more or less the same thing under the hood, but the name itself - EndEdit - makes its functionality much more understandable and it's easier to remember.
This is how it works now:
private void cbxCheckAll_Click(object sender, EventArgs e)
{
if (dgvTable.Rows.Count == 0) return;
try {
bool checkAll = cbxCheckAll.Checked;
foreach (DataGridViewRow row in dgvTable.Rows) {
row.Cells[0].Value = checkAll;
}
}
finally {
OptionsChanged?.Invoke(this, EventArgs.Empty);
}
}
private void DGSelection_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return;
bool currentValue = (bool)dgvTable[0, e.RowIndex].Value;
dgvTable[0, e.RowIndex].Value = !currentValue;
}
private void DgvTableCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (!dgvTable.IsHandleCreated) return;
cbxCheckAll.Checked = dgvTable.Rows.OfType<DataGridViewRow>().All(r => (bool)r.Cells[0].Value == true);
dgvTable.BeginInvoke(new Action(() => dgvTable.RefreshEdit()));
OptionsChanged?.Invoke(this, EventArgs.Empty);
}

sending data to event handler when the event is called programmatically

protected void Page_Load(object sender, EventArgs e)
{
Team T = new Team();
string[] TLeaders = T.GetAllTeamLeaders(Session["USER_EMAIL"].ToString(), Session["ProjectID"].ToString());
for (int i = 0; i < TLeaders.Length; i++)
{
System.Web.UI.HtmlControls.HtmlGenericControl createDiv =new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDiv.Style.Add(HtmlTextWriterStyle.BorderStyle, "Solid");
createDiv.Style.Add(HtmlTextWriterStyle.BorderColor, "lightblue");
createDiv.Style.Add(HtmlTextWriterStyle.BorderWidth, "1px");
createDiv.Style.Add(HtmlTextWriterStyle.Height, "100px");
createDiv.Style.Add(HtmlTextWriterStyle.Width, "1350px");
createDiv.Style.Add(HtmlTextWriterStyle.MarginTop, "20px");
createDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "white");
DivRate.Controls.Add(createDiv);
Label LeaderName = new Label();
LeaderName.Text = TLeaders[i];
LeaderName.Style.Add("margin-left", "600px");
LeaderName.Style.Add("color","gray");
LeaderName.Style.Add("font-size","20px;");
LeaderName.Style.Add("margin-top", "10px");
LeaderName.Style.Add("position", "absolute");
createDiv.Controls.Add(LeaderName);
RadioButtonList Rate = new RadioButtonList();
ListItem bad = new ListItem();
ListItem fair = new ListItem();
ListItem good= new ListItem();
ListItem veryGood = new ListItem();
ListItem excellent = new ListItem();
bad.Value = "1";
bad.Text = "Bad";
fair.Value = "2";
fair.Text = "Fair";
good.Value = "3";
good.Text = "Good";
veryGood.Value = "4";
veryGood.Text = "Very Good";
excellent.Value = "5";
excellent.Text = "Excellent";
Rate.AutoPostBack = true;
Rate.Items.Add(bad);
Rate.Items.Add(fair);
Rate.Items.Add(good);
Rate.Items.Add(veryGood);
Rate.Items.Add(excellent);
Rate.Attributes.Add("onchange", "return LeaderName('"+TLeaders[i]+"');");
Rate.SelectedIndexChanged += new EventHandler(CheckChange("s"));
Rate.RepeatColumns=5;
Rate.Width = 10;
Rate.Height = 10;
Rate.CssClass = "RateClass";
createDiv.Controls.Add(Rate);
}
}
so in this code I create a div and I place inside it a label and a Radio Button List however what i want to do is to create an event handler and send a data to it when i call it i call it like this:
Rate.SelectedIndexChanged += new EventHandler(CheckChange("s"));
and this is the event handler:
protected void CheckChange(string s)
{
ScriptManager.RegisterStartupScript(Page, typeof(Page), "", "fun('" + s + "')", true);
}
It give me an error "method name expected" when I send the data like this
any solution?

Stay open context menu after click

I've got datagrid with context menu. It is initialized programatically:
contextMenu = new ContextMenu();
foreach (var col in this.Columns)
{
var checkBox = new MenuItem()
{
Header = col.Header
};
Binding myBinding = new Binding("Visibility");
myBinding.Mode = BindingMode.TwoWay;
myBinding.Converter = new IsCheckedToVisibilityConverter();
checkBox.DataContext = col;
checkBox.SetBinding(MenuItem.IsCheckedProperty, myBinding);
checkBox.Click += checkBox_Click;
checkBox.Checked += checkBox_Checked;
checkBox.Unchecked += checkBox_Unchecked;
contextMenu.Items.Add(checkBox);
}
It works great, but i would like to stay open context menu after check\uncheck menuitems. Any ideas ?
After adding checkBox.StaysOpenOnClick = true; works as expected
contextMenu = new ContextMenu();
foreach (var col in this.Columns)
{
var checkBox = new MenuItem()
{
Header = col.Header
};
//binding
Binding myBinding = new Binding("Visibility");
myBinding.Mode = BindingMode.TwoWay;
myBinding.Converter = new IsCheckedToVisibilityConverter();
checkBox.DataContext = col;
checkBox.SetBinding(MenuItem.IsCheckedProperty, myBinding);
checkBox.Click += checkBox_Click;
checkBox.Checked += checkBox_Checked;
checkBox.Unchecked += checkBox_Unchecked;
checkBox.StaysOpenOnClick = true;
contextMenu.Items.Add(checkBox);
}
You can try:
private bool close= true;
private void CheckBox1_CheckedChanged(Object sender, EventArgs e)
{
close= false;
}
private void contextMenu_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
e.Cancel = !close;
CloseContextMenu = true;
}

Menu strip is not shown in form designer, even though its code exists

Last night, I was working on my project in C# by visual studio 2012. Suddenly I encountered a few errors from visual studio and then menu strip went into hiding. Now I haven't menu strip in my form and I lost all it visual option, but I have all it code in my formdesigner.cs file. I can't make all option again because it is hard and Time-consuming and I must create a menu strip by new names.and create all sub items by new names.
How I can resume my lost menu strip to form?
This is a part of my designer code:
this.Main = new System.Windows.Forms.ToolStripMenuItem();
this.userOptionTtm = new System.Windows.Forms.ToolStripMenuItem();
this.changePasswprdTSM = new System.Windows.Forms.ToolStripMenuItem();
this.CalenderOption = new System.Windows.Forms.ToolStripMenuItem();
this.CalenderOption2 = new System.Windows.Forms.ToolStripMenuItem();
this.CalenderOption1 = new System.Windows.Forms.ToolStripMenuItem();
this.hollydays = new System.Windows.Forms.ToolStripMenuItem();
this.ExitTsm = new System.Windows.Forms.ToolStripMenuItem();
this.useroption = new System.Windows.Forms.ToolStripMenuItem();
this.ReportsTSM = new System.Windows.Forms.ToolStripMenuItem();
this.loanListTsm = new System.Windows.Forms.ToolStripMenuItem();
this.FeutureJobsTSM = new System.Windows.Forms.ToolStripMenuItem();
and i have properties for all sub items of menu , that i was created (or defined ) previously. for example :
//
// Main
//
this.Main.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.userOptionTtm,
this.CalenderOption,
this.ExitTsm});
this.Main.Font = new System.Drawing.Font("Segoe UI", 9F);
this.Main.Name = "Main";
this.Main.Size = new System.Drawing.Size(62, 20);
this.Main.Text = "تنظیمات";
//
// userOptionTtm
//
this.userOptionTtm.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.changePasswprdTSM});
this.userOptionTtm.Font = new System.Drawing.Font("Segoe UI", 10F);
this.userOptionTtm.Image = global::TimeManagment.Properties.Resources._0079;
this.userOptionTtm.Name = "userOptionTtm";
this.userOptionTtm.Size = new System.Drawing.Size(165, 24);
this.userOptionTtm.Text = "تنظیمات کاربر";
this.userOptionTtm.Click += new System.EventHandler(this.chengePasswordTtm_Click_1);
and in my form code, I have all code of this menu. for example:
private void FeutureJobsTSM_Click(object sender, EventArgs e)
{
FeutureReportForm.isJobs = true;
FeutureReportForm fr = new FeutureReportForm();
fr.ShowDialog(this);
}
or
private void changePasswprdTSM_Click(object sender, EventArgs e)
{
chengePasswordForm cpf = new chengePasswordForm();
cpf.ShowDialog();
}
thx everybody. I added these lines to Form.Designer.cs file and my problem fixed.
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.menuStrip1.BackColor = System.Drawing.Color.Transparent;
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[]
{ this.Main,this.ReportsTSM });
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.menuStrip1.Size = new System.Drawing.Size(589, 24);
this.menuStrip1.TabIndex = 10;
this.menuStrip1.Text = "menuStrip1";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.Controls.Add(this.menuStrip1);
private System.Windows.Forms.MenuStrip menuStrip1;

Bind ListView to dynamic Accordion

In the page_load I'm creating dynamically the headers using data from SpGetCompanies, which is working fine. Then I'm trying to add a ListView to every dynamically created accordion pane with the data source SpSearchPublicationsTop1.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
SQLConnection dataAccessor = new SQLConnection();
dtCompanies = dataAccessor.SpGetCompanies();
if (dtCompanies.Rows.Count > 0)
{
AccordionPane pn;
Label lblContent;
int j = 0;
for (int i = 0; i < dtCompanies.Rows.Count; i++)
{
lblHeader = new Label();
lblHeader.Text = dtCompanies.Rows[i][1].ToString();
lblContent = new Label();
lblContent.Text = "Hallo";
pn = new AccordionPane();
pn.ID = "Pane" + j;
pn.HeaderContainer.Controls.Add(lblHeader);
ListView view = new ListView();
view.LayoutTemplate = new LayoutTemplate();
view.ItemTemplate = new ItemTemplate();
//view = (ListView)FindControl("lv_result");
view.DataSource = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
view.DataBind();
#region commented stuff
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// //view = (ListView)FindControl("lv_result");
// //column1.Text = dt2.Rows[0][0].ToString();
// //view.Columns.Add(column1);
// //Label lblAcronym = new Label();
// //lblAcronym.Text = dt2.Rows[0][0].ToString();
// //view.DataSource = lblAcronym;
// view.DataSource = dt2;
// view.DataBind();
//}
//listView1.Columns.Add(column1);
//foreach (DataRow dr in dt2.Rows)
//{
// ListViewItem lvi = new ListViewItem(dr[0].ToString()); //1.st column in datatable, instead of 0 you can write column`s name like: ["CustomerID"]
// lvi.SubItems.Add(dr[1].ToString()); //2nd column from datatable
// view.Items.Add(lvi);
//}
//this.Controls.Add(view);
//ListView lv_result = new ListView();
////lv_result.ItemTemplate = new ItemTemplate();
//lv_result.ID = "lvpane" + i;
//lv_result.Visible = true;
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// lv_result.DataSource = dt2;
// lv_result.DataBind();
//}
//var level2 = (ListView)FindControl("lv_result");
//level2.ItemTemplate = view.ItemTemplate;
////level2.DataSource = dt2(e.AccordionItem.DataItemIndex);
////level2.DataBind();
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// level2.DataSource = dt2;
// level2.DataBind();
//}
#endregion
pn.ContentContainer.Controls.Add(view);
//pn.ContentContainer.Controls.Add(lblContent);
Accordion1.Panes.Add(pn);
++j;
}
}
}
}
private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var ol = new HtmlGenericControl("ol");
var li = new HtmlGenericControl("li") { ID = "itemPlaceholder" };
ol.Controls.Add(li);
container.Controls.Add(ol);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var li = new HtmlGenericControl("li");
li.DataBinding += DataBinding;
container.Controls.Add(li);
}
public void DataBinding(object sender, EventArgs e)
{
var container = (HtmlGenericControl)sender;
var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
container.Controls.Add(new Literal() { Text = dataItem.ToString() });
}
}
With the code above the headers from the accordion are working fine, but instead of the ListView data in the content I'm only getting: System.Data.DataRowView
What am I doing wrong?
You are missing a call to:
DataBinder.Eval(container.DataItem, "YouBindingProperty");
Example:
public void DataBinding(object sender, EventArgs e)
{
var genericControl = (HtmlGenericControl)sender;
var container = (ListViewDataItem)container.NamingContainer;
container.Controls.Add(new Literal() { Text = DataBinder.Eval(container.DataItem, "YouBindingProperty") });
}

Categories