I have created a function to dynamically create textboxes based on the amount selected from the textbox, additionally I'm using these textboxes to display data from database. However when the user chooses for exactly five from the dropdownlist, and three textboxes was already there, instead of adding 2 more textboxes, it adds the additional 5 textboxes. What I do in order to just add the additionaly textboxes?
protected void TotalSeal_SelectedIndexChanged(object sender, EventArgs e)
{
populate();
}
public void populate()
{
int count = Convert.ToInt32(TotalSeal.SelectedItem.Value);
for (int i = 0; i < count; i++)
{
if (i < 0)
{
}
else
{
TextBox tx = new TextBox();
tx.MaxLength = 10;
tx.Width = 100;
phSealNum.Controls.Add(tx);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(tx);
}
}
}
UPDATE
public void populate()
{
//ControlCache = new List<Control>();
//phSealNum.Controls.Clear();
int targetCount = Convert.ToInt32(TotalSeal.SelectedItem.Value);
int currentItems = phSealNum.Controls.OfType<TextBox>().Count();
int totalitems = targetCount - currentItems;
if (totalitems <= 7)
{
for (int i = 0; i < totalitems; i++)
{
TextBox tx = new TextBox();
tx.MaxLength = 10;
tx.Width = 100;
phSealNum.Controls.Add(tx);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(tx);
}
}
else
{
lblError.Text = targetCount + " exceeds number of seals";
}
}
Using #indrit-kello logic should be like this:
protected void TotalSeal_SelectedIndexChanged(object sender, EventArgs e)
{
populate();
}
public void populate()
{
int targetCount = Convert.ToInt32(TotalSeal.SelectedItem.Value);
if(targetCount > 7)
targetCount = 7;
int currentItems = 0;//TODO
for (int i = currentItems; i < targetCount; i++)
{
TextBox tx = new TextBox();
tx.MaxLength = 10;
tx.Width = 100;
phSealNum.Controls.Add(tx);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(tx);
}
}
Related
I am taking input from 5 textboxes and sorting the values inserted into the text boxes by putting them into labels and moving the labels around till the values in them are sorted.
I have so far put them into labels, but I don't know how to move he labels on button click and let the labels move to get sorted.
This is one way of simulating the algorithm of insertion sort.
my code so far for button click :
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "insertion sort")
{
for ( i = 0; i < 5; i++)
{
if (c != 0)
{
myLabel[i].Dispose();
}
myLabel[i] = new Label();
myLabel[i].Location = new Point(a, b);
myLabel[i].Width = 70;
myLabel[i].Height = 70;
myLabel[i].BackColor=Color.White;
myLabel[i].BorderStyle = BorderStyle.FixedSingle;
panel1.Controls.Add(myLabel[i]);
a = a + 100;
myLabel[i].Visible = true;
}
timer1.Start();
c++;
}
myLabel[0].Text = textBox1.Text;
myLabel[1].Text = textBox5.Text;
myLabel[2].Text = textBox4.Text;
myLabel[3].Text = textBox3.Text;
myLabel[4].Text = textBox2.Text;
}
public partial class Form1 : Form
{
Label[] myLabel=new Label[5];
int a = 30; //x coordinates of first label in label1 array
int b = 125; //y coordinates of first label in label1 array
int c = 0;
int k = 0;
int n = 0;
int j = 1;
int i;
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Selection Sort");
comboBox1.Items.Add("Insertion Sort");
}
you need to sort value of textbox and then put value in labels. Something like this :
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "insertion sort")
{
for ( i = 0; i < 5; i++)
{
if (c != 0)
{
myLabel[i].Dispose();
}
myLabel[i] = new Label();
myLabel[i].Location = new Point(a, b);
myLabel[i].Width = 70;
myLabel[i].Height = 70;
myLabel[i].BackColor=Color.White;
myLabel[i].BorderStyle = BorderStyle.FixedSingle;
panel1.Controls.Add(myLabel[i]);
a = a + 100;
myLabel[i].Visible = true;
}
timer1.Start();
c++;
}
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>(textBox1.Text, textBox1.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox2.Text, textBox2.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox3.Text, textBox3.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox4.Text, textBox4.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox5.Text, textBox5.Text.Value));
list.Sort(Compare2);
int increment = 0;
foreach(var item in list)
{
myLabel[increment].Text=item.Value;
increment++;
}
}
static int Compare2(KeyValuePair<string, string> a, KeyValuePair<string, string> b)
{
return a.Value.CompareTo(b.Value);
}
Hi i am new to programming in c# wpf i just need to create a datagrid of some details i made it and the one major task is the while adding the serial number will be incremented as 1,2,3,4,etc.as when i remove an record from the datagrid the serial number to rearrange according to it eg:sno:1,2,3,4,5,6.
after removing the 3rd row it should be 1,2,3,4,5 instaed of 1,2,4,5,6.
similarly for inserting a row between 1,2,3 after adding it should be 1,2,3,4 task is row nust be added between 2 and 3 the new row help need
void mbtninsertstep_Click(object sender, RoutedEventArgs e) {
int rowindex = mdatagridedit.Items.IndexOf(mdatagridedit.CurrentCell);
if (rowindex >= 0) {
int rowcount = programtable.Rows.Count;
msteps.Add(new Steps { mStepno = count, mPosition = "0",
mRepeat = "NONE", mCount = "1", mAftercut = "NONE" });
int p = rowindex + 1;
for (int i = 0; i < rowcount + 1; i++) {
programtable.Rows[i][0] = p++;
} edited = true;
}
}
delete button code
insert button code.
void mbtndeletestep_Click(object sender, RoutedEventArgs e)
{
int deleterow;
DataGridView dg = new DataGridView();
// msteps.Remove((Steps)mdatagridedit.SelectedItem);
int rowindex = dg.CurrentRow.Index;
if (rowindex >= 0) {
int rowcount = programtable.Rows.Count;
int temp = dg.CurrentCell.RowIndex;
programtable.Rows.RemoveAt(temp);
int p = temp + 1;
for (int i = rowindex; i < rowcount - 1; i++) {
programtable.Rows[i][0] = p++;
}
int RowCountAfterDeleting = programtable.Rows.Count;
}
//int p = mdatagridedit.Items.Count;
// if (mdatagridedit.SelectedItem == null) {
// System.Windows.Forms.MessageBox.Show("Select an row");
// } else {
//msteps.RemoveAt(mdatagridedit.SelectedIndex);
//int p = mdatagridedit.SelectedIndex + 1;
// for(int i = mdatagridedit.SelectedIndex;
i < mdatagridedit.Items.Count - 1; i++){
// Steps step = new Steps();
// step.mStepno = p - 1;
// } int p1 = programtable.Rows.Count;
//}
}
I have been trying to create a chess strategy application. I seem to be having issues with trying to get the label1 control to populate during run time. I am actually pretty new to the idea of dynamically creating events like 'mouse enter, mouse leave' How do I get the label to show the coordinates in the mouse enter event
int currentXposition, currentYposition;
const string positionLabel = "Current Position: ";
private void Test_Load(object sender, EventArgs a)
{
var temp=Color.Transparent; //Used to store the old color name of the panels before mouse events
var colorName = Color.Red; //Color used to highlight panel when mouse over
int numBlocks = 8; //Used to hold the number of blocks per row
int blockSize=70;
//Initialize new array of Panels new
string[,] Position = new string[8, 8];
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
string Alphabet = "A,B,C,D,E,F,G,H";
string Numbers ="1,2,3,4,5,6,7,8";
string[] alphaStrings = Numbers.Split(',');
string[] numStrings=Numbers.Split(',');
// b = sub[0];
int FirstValue, SecondValue;
//Store Position Values
for (int firstValue = 0; firstValue < 8; ++firstValue)
{
FirstValue = Alphabet[firstValue];
for (int SecValue = 0; SecValue < 8; ++SecValue)
{
SecondValue = Numbers[SecValue];
Position[firstValue, SecValue] = alphaStrings[firstValue] + numStrings[SecValue];
}
}
//Loop to create panels
for (int iRow = 0; iRow < numBlocks; iRow++)
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
Panel p = new Panel();
//set size
p.Size = new Size(blockSize, blockSize);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(blockSize *iRow+15, blockSize * iColumn+15);
chessBoardPanels[iRow, iColumn] = p;
chessBoardPanels[iRow,iColumn].MouseEnter += (s,e) =>
{
currentXposition = iRow;
currentYposition = iColumn;
var oldColor = (s as Panel).BackColor;
(s as Panel).BackColor = colorName;
temp = oldColor;
label1.Text = Position[iRow, iColumn];
};
chessBoardPanels[iRow, iColumn].MouseLeave += (s, e) =>
{
(s as Panel).BackColor = temp;
};
groupBox1.Controls.Add(p);
}
}
Try this.. It was not populating because of a out of range.. iRow always = 8...
Add this class to your project.
public class ChessSquare
{
public string Letter { get; set; }
public int Number { get; set; }
public Color Color { get; set; }
public string Position
{
get { return string.Format("{0}{1}", Letter, Number); }
}
public ChessSquare()
{
}
public ChessSquare(string letter, int number)
{
Letter = letter;
Number = number;
}
}
Replace the FormLoad method with this:
int blockSize = 20;
Panel[,] chessBoardPanels = new Panel[8, 8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
ChessSquare sq = new ChessSquare(((char)(65+i)).ToString(), j);
sq.Color = (i + (j % 2)) % 2 == 0 ? Color.AliceBlue : Color.White;
Panel p = new Panel()
{ Size = new Size(blockSize, blockSize),
BackColor = sq.Color,
Tag = sq,
Location = new Point(blockSize * i + 15, blockSize * j+15),
};
p.MouseEnter+=new EventHandler(squareMouseEnter);
p.MouseLeave += new EventHandler(squareMouseLeave);
chessBoardPanels[i, j] = p;
groupBox1.Controls.Add(p);
}
}
And add those two methods to your code:
void squareMouseEnter(object sender, EventArgs e)
{
Panel p = (Panel)sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = Color.Aqua;
label1.Text = string.Format("Current position: {0}", sq.Position);
}
void squareMouseLeave(object sender, EventArgs e)
{
Panel p = (Panel) sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = sq.Color;
}
I there are several ways of doing it... This one is pretty straight forward.
I have a Button that creates a list of TextBoxes Dynamically and I also have a Button that submits the information. However I don't know how to access the values of the Textboxes. Below is the code:
if (IsPostBack)
{
ViewState["count"] = Convert.ToInt32(ViewState["count"]) + 1;
int Count = int.Parse(string.Format("{0}", ViewState["count"]));
var lstTextBox = new List<TextBox>();
for (int i = 0; i < Counter; i++)
{
TextBox txtbx = new TextBox();
txtbx.ID = string.Format("txtbx{0}", i);
// txtbx.AutoPostBack = true;
lstTextBox.Add(txtbx);
//txtbx.Text = "initial value";
}
Session["lstTextBox"] = lstTextBox;
}
protected void Button1_Click(object sender, EventArgs e)
{
int total = Counter;
for (int i = 0; i < total; i++)//Calls to createbox
CreateTextBox(i);
//Label1.Text = Counter.ToString();
if (Counter == 4)
{
Button1.Visible = false;
}
}
private int Counter
{
get { return Convert.ToInt32(ViewState["count"] ?? "0"); } //Fields button counter
set { ViewState["count"] = value; }
}
private void CreateTextBox(int j) //Creates the fields / cells
{
var box = new TextBox();
box.ID = "Textbox" + j;
box.Text = "Textbox" + j;
var c = new TableCell();
c.Controls.Add(box);
r.Cells.Add(c);
table1.Rows.Add(r);
}
How would like to have Button2 grab the values.
Thank you in advance!!
do it like this
foreach(Control c in YourControlHolder.Controls)
{
if(c is TextBox)
{
//your code here.
}
}
I using this code for sum selected cells. Its work good but when user selecte cell where is letter is throws exceptions : ) how can i secure when in selectet cells is letters dont make sum
i asked same question but there i cannot add my code
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
if (!dataGridView1.SelectedCells.Contains(dataGridView1.Rows[i].Cells["cLoadName"]))
{
float nextNumber = 0;
float sumNumbers = 0;
nextNumber = float.Parse(dataGridView1.SelectedCells[i].FormattedValue.ToString());
sumNumbers += nextNumber;
tsslSumSelected.Text = "ჯამი: " + sumNumbers;
tsslTotalSelected.Text = "მონიშნული: " + dataGridView1.SelectedCells.Count.ToString();
}
else
{
}
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
if (!dataGridView1.SelectedCells.Contains(dataGridView1.Rows[i].Cells["cLoadName"]))
{
float nextNumber = 0;
float sumNumbers = 0;
if (float.TryParse(dataGridView1.SelectedCells[i].FormattedValue.ToString(), out nextNumber))
sumNumbers += nextNumber;
tsslSumSelected.Text = "ჯამი: " + sumNumbers;
tsslTotalSelected.Text = "მონიშნული: " + dataGridView1.SelectedCells.Count.ToString();
}
else
{
}
}
}
public void ComputeGridTot()
{
try
{
decimal qty= 0;
decimal price = 0;
decimal tax = 0;
decimal Total = 0;
for (int i = 0; i < drGrdView1.Rows.Count; i++)
{
if (drGrdView1.Rows[i].Cells[7].Value.ToString() == blcnt.ToString())
{
qty += Convert.ToDecimal(drGrdView1.Rows[i].Cells[3].Value);
price += Convert.ToDecimal(drGrdView1.Rows[i].Cells[4].Value);
tax += Convert.ToDecimal(drGrdView1.Rows[i].Cells[5].Value);
Total += Convert.ToDecimal(drGrdView1.Rows[i].Cells[6].Value);
}
}
lblGTax.Text = tax.ToString();
lblGQty.Text = qty.ToString();
lblGPrice.Text = price.ToString();
lblGTot.Text = Total.ToString();
}
catch
{
}
}