Can I add a control to a ContextMenuStrip? - c#

Is it possible to add a control like CheckBox to ContextMenuStrip?
I want to be able to tick a few options BEFORE I select the menu option.
This what I do now, but I have commented out where I try to add chkBox - as it does not work:
DataGridView gridView = sender as DataGridView;
ContextMenuStrip my_menu = new ContextMenuStrip();
int colIndex = gridView.HitTest(e.X, e.Y).ColumnIndex;
Globals.PlotColumnIndex = colIndex;
my_menu.Items.Add("New plot").Name = "New plot";
my_menu.Items.Add("New trades plot").Name = "New trades plot";
my_menu.Items.Add("Add to existing plot").Name = "Add to existing plot";
my_menu.Items.Add("Add to existing plot Y2").Name = "Add to existing plot Y2";
CheckBox chkBox = new CheckBox();
chkBox.Text = "Option 1";
//my_menu.Controls.Add(chkBox);
my_menu.Show(gridView, new Point(e.X, e.Y));
my_menu.ItemClicked += new ToolStripItemClickedEventHandler(my_menu_ItemClicked);

Using a ToolStripControlHost is one option:
var cb = new CheckBox();
cb.Text = "Checkbox 1";
var tch = new ToolStripControlHost(cb);
menu.Items.Add(tch);

Related

How to get correct datagridview valid row/column index in MDIParent in c#

I have a datagridview on a form which when I click, gives me the correct row/column index clicked:
Clicking on verify [third column, first row, gives the above].
But when this form is called from an MDI parent, clicking on thesame column three, row one (Verify) gives this:
Below is the behind code for the form:
var result = new DAO().RetrieveAllProjects().Select(r => new { r.Name }).ToList();
dataGridView1.DataSource = result;
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.HeaderText = "";
btn.Text = "View/Edit";
btn.Name = "edit";
btn.UseColumnTextForButtonValue = true;
DataGridViewButtonColumn btn2 = new DataGridViewButtonColumn();
btn2.HeaderText = "";
btn2.Text = "Verify";
btn2.Name = "verify";
btn2.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(btn);
dataGridView1.Columns.Add(btn2);
dataGridView1.Columns[0].Width = 290;
dataGridView1.AutoSize = true;
dataGridView1.CellClick += dataGridView1_CellClick;
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(string.Format("ColumnIndex:{0}, RowIndex: {1}", e.ColumnIndex, e.RowIndex));
}
And it's called from the mdi parent this way:
projectsListForm pLF = new projectsListForm();
pLF.MdiParent = this;
pLF.Show();
How can I make sure that the correct row/column is highlighted on the mdi parent
for some reason[s] when MdiParent is used, two round of databinding happens in dataGridView1 (DataGridView DataBindingComplete event is triggered). "Name" column gets unnecessary removed and added (DataGridView ColumnAdded and ColumnRemoved events). To stop this behavior I disabled columns auto-generation after seting DataSource:
dataGridView1.DataSource = ...;
dataGridView1.AutoGenerateColumns = false;
A safer option is to work with columns by names, not by indices

How to get selected index of toolstripbutton in c#

I have a toolstrip control on a form and i programatically add buttons to the toolstrip control using the below code
toolStrip1.Visible = true;
ToolStripItem t = new ToolStripButton();
t.Text = client.EndPoint.ToString();
t.TextImageRelation = TextImageRelation.ImageAboveText;
t.BackgroundImage = Image.FromFile("" + Application.StartupPath + "ps1_new.PNG");
t.AutoSize = false;
t.Height = 67;
t.Width = 70;
t.BackgroundImageLayout = ImageLayout.Stretch;
t.TextAlign = ContentAlignment.BottomCenter;
toolStrip1.Items.Add(t);
Now i m trying to get the index of the toolstrip button when i click on it
note i can get the text of the clicked toolstripbutton using
e.ClickedItem.Text;
There isn't an index property on the toolstripitem click but you could do something like this
private void ToolStrip1_ItemClicked(object sender, EventArgs e)
{
MessageBox.Show(e.ClickedItem.Tag)
}
Where the Tag property is something you set as the index.

Add Controls to Control.Collection

I´m trying to create new Controls (TextBox, ComboBox and CheckBox) to a Control.ControlCollection, but it doesn´t work. Normally my WinForm would pass its controls to that method, but now I´m trying to write a unit test for it.
Here´s the code:
TestClass target = new TestClass();
Control.ControlCollection controls = null;
CheckBox checkBox = new CheckBox();
checkBox.Name = "SomeCheckBox";
checkBox.Checked = true;
ComboBox comboBox = new ComboBox();
comboBox.Name = "SomeComboBox";
checkBox.Text = "Some text in CB";
TextBox count = new TextBox();
count.Name = "CountTextBox";
count.Text = "20";
TextBox date = new TextBox();
date.Name = "DateNow";
date.Text = System.DateTime.Now.ToString("dd.MM.yyyy");
controls.AddRange(new Control[] {checkBox, comboBox, count, date });
string actual;
actual = target.saveEverything(controls);
Test fails in the AddRange-Row. What mistake did I make?
Ok, I´m stupid. I forgot to initilize controls.
Control con = new Control();
Control.ControlCollection controls = new Control.ControlCollection(con);

How to create EventHandler for dynamically created buttons (for each one) C# VS2010

So, I have a form in which all buttons and textboxes and labes are dynamically generated
Code:
private void LoadElements()
{
int Y = 30;
int j = 0;
con.Open();
OleDbCommand populate = new OleDbCommand("SELECT * FROM Users", con);
OleDbDataReader reader = populate.ExecuteReader();
while (reader.Read())
{
b = new Button();
b.Text = "Delete";
b.Name = reader["Username"].ToString();
b.BackColor = Color.DarkOrange;
b.ForeColor = Color.Black;
b.Location = new Point(240, Y);
b.FlatStyle = FlatStyle.Flat;
LB.Add(b);
tb1 = new TextBox();
tb1.Location = new Point(10, Y);
TB1.Add(tb1);
tb1.Text = reader["Username"].ToString();
tb2 = new TextBox();
tb2.Location = new Point(120, Y);
tb2.Text = reader["Password"].ToString();
TB2.Add(tb2);
Y += 30;
j++;
}
foreach (Button BTN in LB) // <- this is a globaly declared List<Button>
{
this.Controls.Add(BTN);
BTN.Click += new EventHandler(BTN_Click);
}
foreach (TextBox text1 in TB1) // <= -||- List<TextBox>
{ this.Controls.Add(text1); }
foreach (TextBox text2 in TB2) // -||-
{ this.Controls.Add(text2); }
// MORE CODE UNDER
}
As you may or may not have noticed, the whole form is a "superadmin" type of form, all users and passwords are loaded from database onto it. I want to be able to have a reference to the created buttons, when a Delete button is clicked I want the program to go into the database and search "WHERE [Username] LIKE" + button.Name + ""(because the button name is the actually Username); My code creates elements dynamically like this: [Name] [Password] [Delete] in the form of [textbox1] [textbox2] [button]. Problem is whenever I click any of the buttons it only takes reference to the last one created, how could I make the event handler so that it can see every button's respective .name?
The pivotal code is in the event handling procedure - you did not show that. Look at the object sender parameter, and use it accordingly!
void BTN_Click(object sender, EventArgs e)
{
Button b = sender as Button;
if (b!=null)
{
//that's your button, with the properties created in the loop.
}
}
It looks like your looking for this code.
b.Click += new EventHandler(b_Click);
Add it into your button creation...
while (reader.Read())
{
b = new Button();
b.Text = "Delete";
b.Name = reader["Username"].ToString();
b.BackColor = Color.DarkOrange;
b.ForeColor = Color.Black;
b.Location = new Point(240, Y);
b.FlatStyle = FlatStyle.Flat;
***b.Click += new EventHandler(b_Click);***
LB.Add(b);
}

Creating dynamic controls on Page_LoadComplete

I have three drop down lists and depending on the values selected in the lists I create dynamic controls accordingly. Everything displays properly but when I click on the dynamically created button the events are not firing. I am using the Page_LoadComplete to create the dynamic controls because I need to the values from the DDL's. Is this the reason for my button events not firing?
protected void Page_LoadComplete(object sender, EventArgs e)
{
queries = new clsFormQueries();
if (HttpContext.Current.User.IsInRole("Admin"))
{
if (!Page.IsPostBack)
{
List<Sport> sports = ComboBoxOptions.getSports();
DropDownList temp = (DropDownList)loginView2.FindControl("Sport");
temp.DataSource = sports;
temp.DataTextField = "Name";
temp.DataValueField = "id";
temp.DataBind();
DropDownList teamsDD = (DropDownList)loginView2.FindControl("Team");
List<Team> teamsList = ComboBoxOptions.getTeamsBySportId(Convert.ToInt32(temp.SelectedValue));
teamsDD.DataSource = teamsList;
teamsDD.DataTextField = "fullName";
teamsDD.DataValueField = "teamId";
teamsDD.DataBind();
DropDownList existingPlayers = (DropDownList)loginView2.FindControl("ExistingPlayers");
List<Player> players = ComboBoxOptions.getPlayersBySport(Convert.ToInt32(temp.SelectedValue), Convert.ToInt32(teamsDD.SelectedValue));
existingPlayers.DataSource = players;
existingPlayers.DataTextField = "fullName";
existingPlayers.DataValueField = "playerid";
existingPlayers.DataBind();
//if (existingPlayers.SelectedValue != "" && temp.SelectedValue != "")
//{
// DataTable updates = queries.GetPlayerUpdate(Convert.ToInt32(existingPlayers.SelectedValue), Convert.ToInt32(temp.SelectedValue));
// if (updates.Rows.Count > 0)
// CreateUpdatesHTML(updates);
//}
}
DropDownList temp2 = (DropDownList)loginView2.FindControl("Sport");
DropDownList existingPlayers2 = (DropDownList)loginView2.FindControl("ExistingPlayers");
if (existingPlayers2.SelectedValue != "" && temp2.SelectedValue != "")
{
DataTable updates = queries.GetPlayerUpdate(Convert.ToInt32(existingPlayers2.SelectedValue), Convert.ToInt32(temp2.SelectedValue));
if (updates.Rows.Count > 0)
CreateUpdatesHTML(updates);
}
}
}
private void CreateUpdatesHTML(DataTable updates)
{
foreach (DataRow update in updates.Rows)
{
int playerUpdateId = (int)update["playerUpdateId"];
string updateText = update["PlayerUpdate"].ToString();
TextBox tb = new TextBox();
tb.ID = "UpdateText" + playerUpdateId;
tb.TextMode = TextBoxMode.MultiLine;
tb.Rows = 5;
tb.Text = updateText;
tb.CssClass = "span5";
Button btnDelete = new Button();
btnDelete.Click += new EventHandler(btnDelete_Click);
btnDelete.ID = "Delete"+playerUpdateId.ToString();
btnDelete.Text = "Delete";
btnDelete.CssClass = "btn btn-info";
Button btnUpdate = new Button();
btnUpdate.Click += new EventHandler(btnUpdate_Click);
btnUpdate.ID = "Update"+playerUpdateId.ToString();
btnUpdate.Text = "Update";
btnUpdate.CssClass = "btn btn-info";
HtmlGenericControl div2 = new HtmlGenericControl("div");
div2.Attributes.Add("class", "pull-right span5");
div2.Controls.Add(btnDelete);
div2.Controls.Add(btnUpdate);
HtmlGenericControl hr = new HtmlGenericControl("hr");
HtmlGenericControl br = new HtmlGenericControl("br");
existingUpdates.Controls.Add(tb);
existingUpdates.Controls.Add(div2);
existingUpdates.Controls.Add(br);
existingUpdates.Controls.Add(hr);
}
}
My guess is that since you have wrapped the logic for your Page_LoadComplete event inside of a n if(!Page.IsPostBack), since the click of the button causes a postback, your dynamically created controls are not recreated properly (read: no click event handling is wired up). You need to have logic on every invocation of Page_LoadComplete (non-postback or postback) that recreates the dynamic controls and wires up their events.

Categories

Resources