I created a panel with a button "add" and a button "delete". If you click on "add" a panel is created right below this header, you can create as much as you want, they are listed.
On each panel there is a checkbox and I would like to delete the panel if the checkbox is checked once the button delete is clicked.
I can get the intuition of a loop : for, but still too novice to get through this without a little tip.
-
public partial class Test_auto : Form
{
ArrayList strategyFutureList = new ArrayList();
public Test_auto()
{
InitializeComponent();
Instance = this;
}
//Create a new future strategy
public void CreateStrategyFuture()
{
ConsoleStrategyItem strategyItemFuture = new ConsoleStrategyItem();
strategyItemFuture.Location = new Point(3, 3);
futureContainer.Height += 85;
strategyFutureList.Add(strategyItemFuture);
futureContainer.Controls.Add(strategyItemFuture);
ConsoleStrategyItem.Instance.txtStrategyName.Text = "Strat Future " + strategyFutureList.IndexOf(strategyItemFuture) + " ";
ConsoleStrategyItem.Instance.Name = "strategyFuture" + strategyFutureList.IndexOf(strategyItemFuture);
ConsoleStrategyItem.Instance.cbxDeleteStrategy.Name = "cbxDeleteFuture" + strategyFutureList.IndexOf(strategyItemFuture);
}
//Makes it appear
private void btnAddStrategyFuture_Click_1(object sender, EventArgs e)
{
CreateStrategyFuture();
}
//Delete a-some selected strategies
public void DeleteStrategyFuture()
{
for (int i = 0; i < strategyFutureList.Count; i++)
{
if (ConsoleStrategyItem.Instance.cbxDeleteStrategy.Checked = true)
{
}
}
}
private void btnDeleteStrategyFuture_Click(object sender, EventArgs e)
{
DeleteStrategyFuture();
}
}
you don't have to create a separate ArrayList to maintain the list of UserControls being added to the futureContainer, you can simply iterate through the Controls collection of it.
simply do this in your DeleteStrategyFuture() method
public void DeleteStrategyFuture()
{
var length=futureContainer.Controls.Count;
foreach(int i=0; i< length; i++)
{
if(futureContainer.Controls[i].GetType()==typeof(ConsoleStrategyItem))
{
bool isChecked =((ConsoleStrategyItem)futureContainer.Controls[i])
.Instance.cbxDeleteStrategy.Checked;
if(isChecked)
{
futureContainers.Controls.Remove(futureContainers.Controls[i]);
}
}
}
}
Related
I want to delete listview item from the main form
after I click on btn in another form
How can I do it?
Main Form
private void DeleteSelectedProductRclick_Click(object sender, EventArgs e)
{
int id = int.Parse(ProductListView.SelectedItems[0].SubItems[0].Text);
string prodname = ProductListView.SelectedItems[0].SubItems[1].Text;
string prodid = ProductListView.SelectedItems[0].SubItems[2].Text;
string cutsentence = null;
for (int i = 7; i >= 1; i--)
{
cutsentence = FirstWords(prodname, i);
if (cutsentence.Length <= 45)
{
cutsentence = cutsentence + " ...";
i = 0;
}
}
DeleteProductForm mg = new DeleteProductForm(id, cutsentence, prodid);
mg.Show();
}
Sec Form
private void Yesbtn_Click(object sender, EventArgs e)
{
EbaySellBL.EbayProduct.DeleteProduct(this.ID);
this.Close();
//ProductListView.SelectedItems[0].Remove();
}
You can make a control (your listview) public by opening the Properties tab in the winform designer and by changing the "Modifiers" property to "Public".
Now you can access it from another form.
More here
guys i am creating dynamic TextBoxes everytime a button is clicked. but once i have as many text boxes as i want.. i want to save these value Database Table.. Please guide how to save it into DB
public void addmoreCustom_Click(object sender, EventArgs e)
{
if (ViewState["addmoreEdu"] != null)
{
myCount = (int)ViewState["addmoreEdu"];
}
myCount++;
ViewState["addmoreEdu"] = myCount;
//dynamicTextBoxes = new TextBox[myCount];
for (int i = 0; i < myCount; i++)
{
TextBox txtboxcustom = new TextBox();
Literal newlit = new Literal();
newlit.Text = "<br /><br />";
txtboxcustom.ID = "txtBoxcustom" + i.ToString();
myPlaceHolder.Controls.Add(txtboxcustom);
myPlaceHolder.Controls.Add(newlit);
dynamicTextBoxes = new TextBox[i];
}
}
You have to recreate the dynamical controls in Page_Load at the latest, otherwise the ViewState is not loaded correctly. You can however add a new dynamical control in an event handler(which happens after page_load in the page's lifefycle).
So addmoreCustom_Click is too late for the recreation of all already created controls, but it's not tool late to add a new control or to read the Text.
So something like this should work(untested):
public void Page_Load(object sender, EventArgs e)
{
if (ViewState["addmoreEdu"] != null)
{
myCount = (int)ViewState["addmoreEdu"];
}
addControls(myCount);
}
public void addmoreCustom_Click(object sender, EventArgs e)
{
if (ViewState["addmoreEdu"] != null)
{
myCount = (int)ViewState["addmoreEdu"];
}
myCount++;
ViewState["addmoreEdu"] = myCount;
addControls(1);
}
private void addControls(int count)
{
int txtCount = myPlaceHolder.Controls.OfType<TextBox>().Count();
for (int i = 0; i < count; i++)
{
TextBox txtboxcustom = new TextBox();
Literal newlit = new Literal();
newlit.Text = "<br /><br />";
txtboxcustom.ID = "txtBoxcustom" + txtCount.ToString();
myPlaceHolder.Controls.Add(txtboxcustom);
myPlaceHolder.Controls.Add(newlit);
}
}
Just enumerate the PlaceHolder-Controls to find your TextBoxes or use Linq:
private void saveData()
{
foreach (TextBox txt in myPlaceHolder.Controls.OfType<TextBox>())
{
string text = txt.Text;
// ...
}
}
Quick and dirty way would be to just iterate the Form collection looking for proper values:
if (Page.IsPostBack)
{
string name = "txtBoxcustom";
foreach (string key in Request.Form.Keys)
{
int index = key.IndexOf(name);
if (index >= 0)
{
int num = Int32.Parse(key.Substring(index + name.Length));
string value = Request.Form[key];
//store value of txtBoxcustom with that number to database...
}
}
}
To get values of dynamically created controls on postback you need to recreate those controls on Page_Init event
Then view state of those controls will be loaded and you will get controls and there values.
public void Page_Init(object sender, EventArgs e)
{
addControls(myCount);
}
I hope this will resolve your problem
Happy coding
I need to make a ListBox that displays how often a Button is clicked.
The user chooses how many buttons are available to click. Here is what I've tried:
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
for (int i = 0; i < freq_array[clicked]; i++)
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
freq_array uses the 'clicked' variable to add to the frequency that button has been clicked. Or, it's supposed to.
When I debug it, 'clicked' always comes out to 0. I want 'clicked' to equal the text value of the button that's clicked. When I try to run the program, I get an error saying "Input string was not in correct format."
Edit:
I was able to fix my program with help from you guys. I realized I didn't show enough of my code to be clear enough, and I apologize for that. I had to add some things and move things around and got it soon enough. Thank you all.
Here is the code just for those who may need help in the future:
public partial class Form1 : Form
{
int[] freq_array = new int[11];
int[] numList = new int[11];
int oBase = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
invisiblity();
}
private void invisiblity()
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
ctrl.Visible = false;
}
}
private void btnSetBase_Click(object sender, EventArgs e)
{
Form2 frmDialog = new Form2();
frmDialog.ShowDialog(this);
if (frmDialog.DialogResult == DialogResult.OK)
{
oBase = frmDialog.Base;
//lblOutDigits.Text = oBase.ToString();
for (int i = 0; i < oBase; i++)
{
numList[i] = i;
}
}
ShowBaseButtons(oBase);
}
private void ShowBaseButtons(int last_digit)
{
invisiblity();
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
if (int.Parse(ctrl.Text) <= last_digit - 1)
ctrl.Visible = true;
}
}
private void btnN_Click(object sender, EventArgs e)
{
lblOutDigits.Text += ((Button)(sender)).Text;
int clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
}
private void btnShowFreq_Click(object sender, EventArgs e)
{
lstFrequencies.Items.Clear();
for (int i = 0; i < oBase; i++)
lstFrequencies.Items.Add(numList[i] + " \t\t\t" + freq_array[i]);
}
Your code should work as long as your Button Text is actually just a number. Since what you are trying to do is create an index, what I usually do is use the Tag Property of the control, set it to the Index I want in the designer and then cast that to an Int.
i.e.
if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
freq_array[clicked]++;
I believe what is happening is that you are not initializing your ListBox, This example Code does work using your initial method. Just create a new Form and paste it in and test.
public partial class Form1 : Form
{
ListBox lstFrequencies = new ListBox();
int[] freq_array = new int[10];
public Form1()
{
InitializeComponent();
Size = new Size(400, 400);
lstFrequencies.Location = new Point(150, 0);
lstFrequencies.Size = new Size(150, 200);
Controls.Add(lstFrequencies);
int top = 0;
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Size = new Size(70, 30);
btn.Location = new Point(5, top);
Controls.Add(btn);
top += 35;
btn.Tag = i;
btn.Text = i.ToString();
btn.Click += new EventHandler(btn_Click);
lstFrequencies.Items.Add(i.ToString());
}
}
void btn_Click(object sender, EventArgs e)
{
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked]; //Cleaned up you do not need to iterate your list
// Using my example code
//if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
//{
// freq_array[clicked]++;
// lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
//}
}
}
Your code always comes out to 0 because you never assign last clicked value to button text. Try this code:
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
clicked = Convert.ToInt32(((Button)sender).Text);
lstFrequencies.Items.Add(((Button)sender).Name + " " + ++clicked);
button1.Text = clicked.ToString(); // you lose this line
}
EDIT: Counter from variable member
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
// if you want to display button name, change .Text to .Name
lstFrequencies.Items.Add(((Button)sender).Text + " " + ++clicked);
}
Hi all I am having 2 forms with checkedListBox . On my form1 I will select a few and click on submit where I will load form2, again on Form2 I will have a checkedListBox with the same Items as per in the first form1. Now I would like to check the form2 checkedListBox as per the form1 selected list.
I tried the following code
public class randomClass1
{
public bool IsChecked { get; set; }
public string Name { get; set; }
public randomClass1()
{
this.IsChecked = true;
Name = "name1";
}
}
My button click event on form1 is as follows
private void button1_Click(object sender, EventArgs e)
{
frmChild1 frm = new frmChild1();
List<randomClass1> lst = new List<randomClass1>();
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
lst.Add(new randomClass1());
}
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
randomClass1 obj = (randomClass1)checkedListBox1.Items[i];
if (checkedListBox1.GetItemChecked(i))
{
checkedListBox1.SetItemChecked(i, obj.IsChecked);
}
else
{
obj.IsChecked = false;
checkedListBox1.SetItemChecked(i, obj.IsChecked);
}
}
frm.loadFrom(lst); //unable to retrieve the same when I checked
//frm.loadFrom(lst);
frm.Show();
}
In form2 I tried of creating the same class but I am unable to access that class, can some one help me what should I code in form2 inorder to get the selected items
There are a number of ways to solve this problem.
First off, I'm assuming that Form1 has access to the Form2 object. If it doesn't, something else will need to act as a middleman to get the checkstate data from Form1 to Form2.
Assuming it does, all you need is a public method like:
public void SetList(List<bool> checkmarks)
{
for (int i = 0; i < checkmarks.Count; ++i)
{
checkedListBox1.SetItemChecked(i, checkmarks[i]);
}
}
or however you want that to work. My quick solution is that in Form1 I've got a button click handler that makes a Form2, shows it and sets the list. But whatever... you just need to be able to communicate those states between the two forms. Here's that code:
private void button1_Click(object sender, EventArgs e)
{
var list = new List<bool>();
for (int i = 0; i < checkedListBox1.Items.Count; ++i)
{
list.Add(checkedListBox1.GetItemChecked(i));
}
Form2 f2 = new Form2();
f2.Show();
f2.SetList(list);
}
In production code I'd probably opt for a pattern like MVC and do things differently but this will work.
The idea is no different if you use your randomClass1 class rather than my List<bool>.
Obviously here I've made assumptions such as that both checkedlistboxes have pre-populated items and they're in the same order, etc. etc.
You could certainly send all that data across and create the items dynamically as well. It wasn't clear from your question which you were doing but I assumed the list was already populated with items.
Try using this code:
void button1_Click(object sender, EventArgs e) {
List<randomClass1> items = new List<randomClass1>();
for (int i = 0; i < checkedListBox1.Items.Count; ++i) {
randomClass1 rc = new randomClass1();
rc.Name = checkedListBox1.Items[i].ToString();
rc.IsChecked = checkedListBox1.GetItemChecked(i);
items.Add(rc);
}
frmChild1 frm = new frmChild1();
frm.LoadFrom(items);
frm.Show();
}
which will populate your list of randomClass items with the text from the list box and the checked value.
On the flip side, here is the LoadFrom method to re-populate that list on the second form:
public void LoadFrom(List<randomClass1> items) {
for (int i = 0; i < items.Count; ++i) {
randomClass1 rc = items[i];
checkedListBox1.Items.Add(rc.Name);
checkedListBox1.SetItemChecked(i, rc.IsChecked);
}
}
I'm trying to create a composite ASP.NET control that let's you build an editable control collection.
My problem is that when I press the add or postback button (which does nothing other than to postback the form) any values entered in the text boxes are lost.
I can't get it to work when the number of controls change between postbacks. I need to basically be able to recreate the control tree at two different times in the control life-cycle depending on the view state property ControlCount.
This test can be used to reproduce the issue:
public class AddManyControl : CompositeControl
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
EnsureChildControls();
}
protected override void CreateChildControls()
{
var count = ViewState["ControlCount"] as int? ?? 0;
for (int i = 0; i < count; i++)
{
var div = new HtmlGenericControl("div");
var textBox = new TextBox();
textBox.ID = "tb" + i;
div.Controls.Add(textBox);
Controls.Add(div);
}
ViewState["ControlCount"] = count;
var btnAdd = new Button();
btnAdd.ID = "Add";
btnAdd.Text = "Add text box";
btnAdd.Click += new EventHandler(btnAdd_Click);
Controls.Add(btnAdd);
var btnPostBack = new Button();
btnPostBack.ID = "PostBack";
btnPostBack.Text = "Do PostBack";
Controls.Add(btnPostBack);
}
void btnAdd_Click(object sender, EventArgs e)
{
ViewState["ControlCount"] = (int)ViewState["ControlCount"] + 1;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// If I remove this RecreateChildControls call
// the collection lags behind each postback
// because the count is incremented in the btnAdd_Click event handler
// however, the values are not lost between postbacks
RecreateChildControls();
}
}
If you want to play with ASP.NET's custom controls, you have to play by its rule and its picky! When you start to play with the OnPreRender in a custom control, you know you're on the wrong track 90% of the time.
Generally, the best way to use the ViewState is to declare a property backed up by it, just like the standard ASP.NET controls do (.NET Reflector has been my teacher for years!). This way, it will be read and saved naturally during the event's lifecycle.
Here is a code that seems to do what you want, quite naturally, without any trick:
public class AddManyControl : CompositeControl
{
private void AddControl(int index)
{
var div = new HtmlGenericControl("div");
var textBox = new TextBox();
textBox.ID = "tb" + index;
div.Controls.Add(textBox);
Controls.AddAt(index, div);
}
protected override void CreateChildControls()
{
for (int i = 0; i < ControlsCount; i++)
{
AddControl(i);
}
var btnAdd = new Button();
btnAdd.ID = "Add";
btnAdd.Text = "Add text box";
btnAdd.Click += new EventHandler(btnAdd_Click);
Controls.Add(btnAdd);
var btnPostBack = new Button();
btnPostBack.ID = "PostBack";
btnPostBack.Text = "Do PostBack";
Controls.Add(btnPostBack);
}
private int ControlsCount
{
get
{
object o = ViewState["ControlCount"];
if (o != null)
return (int)o;
return 0;
}
set
{
ViewState["ControlCount"] = value;
}
}
void btnAdd_Click(object sender, EventArgs e)
{
int count = ControlsCount;
AddControl(count);
ControlsCount = count + 1;
}
}
I believe you have to add the control into the view state.