My table in MySQL is like this:
I have a panel in my Form, and I want to create a TextBox for each data on this table and write sikicerik data to that TextBox's text.
Actually I did it but it creates only one TextBox and selects only the first data on the table.
My code is like this:
int count = oku.FieldCount;
reader.Read();
{
for (int i = 0; i < count; i++)
{
TextBox txt1 = new TextBox();
Point txtyer = new Point(x, y);
txt1.Text = reader["sikicerik"].ToString();
txt1.Name = i.ToString();
x = x + 25;
y = y + 25;
panel1.Controls.Add(txt1);
}
}
It creates just one TextBox and writes "5" in it.
How can I do that repeatedly?
What you need to understand is that you need to call reader.Read() after going through each record. Let's say your result data set has 5 records, so in order to read the 1st record, you need to call reader.Read() which would populate the reader object with the appropriate data. In order to read the 2nd record, you need to again call reader.Read(). Something like this:
int count = reader.FieldCount;
for (int i = 0; i < count; i++)
{
reader.Read();
TextBox txt1 = new TextBox();
Point txtyer = new Point(x, y);
txt1.Location = txtyer;
txt1.Text = reader["sikicerik"].ToString();
txt1.Name = i.ToString();
y = y + 25;
panel1.Controls.Add(txt1);
}
The reason why you may not be able to view all TextBoxes is that you are updating both x and y coordinates of the TextBox. What you may probably want to do is just increment the y coordinate as above and all the TextBoxes would appear vertically. You may also want to resize your form so that the TextBoxes don't get hidden.
Also, as #Steve mentioned in the comments above (which I missed), you need to assign the location of the new TextBoxes created as is done in the code above.
I suppose that you get the FieldCount from the reader variable.
Now in this context you should loop over the read and inside the loop create the textbox for each field retrieved by the original query.
Finally, if you don't set the Location property of the TextBoxes they will be created each on top of the others and you see only the topmost one with the latest value obtained in the loop
// Get the number of fields present in the reader....
int count = reader.FieldCount;
// Read one record at time
while(reader.Read())
{
// Create a textbox for each field in the record
for (int i = 0; i < count; i++)
{
TextBox txt1 = new TextBox();
// Set its location on screen
// Probably if you have many fields you need to
// use a better algorithm to calculate x,y position
txt1.Location = new Point(x, y);
txt1.Text = reader[i].ToString();
txt1.Name = i.ToString();
x = x + 25;
y = y + 25;
panel1.Controls.Add(txt1);
}
}
If you want to create textboxes only for the field sikicerik you have two options. The first one is the recommended because it causes less overhead on your database consist in changing the SELECT query used to build the read to
SELECT sikicerik FROM yourTableName
The other option is a simple change to your code. You don't need to loop over FieldCount because you already know that you are interested in only one field
// Read one record at time
while(oku.Read())
{
textBox1.Text = oku["soru"].ToString();
label1.Text = Form2.sinavno;
// Create the single textbox required for the only field required
TextBox txt1 = new TextBox();
// Set its location on screen
txt1.Location = new Point(x, y);
txt1.Text = oku["sikicerik"].ToString();
txt1.Name = i.ToString();
x = x + 25;
y = y + 25;
panel1.Controls.Add(txt1);
// Repeat the loop for each record.
}
Related
I am creating a total of n textbox whenever i enter the value n on a textbox and click on a button in ASP.NET. Im using the below code for that,
int n = Convert.ToInt32(text_flats_blocks.Text);
for (int i = 0; i < n; i++)
{
TextBox MyTextBox = new TextBox();
MyTextBox.ID = "text_" + (i+1);
panel_flats_blocks.Controls.Add(MyTextBox);
MyTextBox.CssClass = "textblock";
Literal lit = new Literal();
lit.Text = "<br /><br />";
panel_flats_blocks.Controls.Add(lit);
}
This works fine and the textboxes are created. Then i enter some values to the textboxes and click on another button. On clicking the second button the values entered in the textboxes should be obtained using C#. But i have created ID for these textboxes using variables like this text_ + (i+1) that creates the names as text_1, text_2 etc. How can i use this as an ID to access the textbox value like id.Text but here the id contains variable. I want to use loop to iterate for n times and access all values from all n textboxes and store them in a list. How can i do this using C#?
You can use FindControl Method
public void SecondButton_Click(object sender, EventArgs)
{
int n = Convert.ToInt32(text_flats_blocks.Text);
for (int i = 0; i < n; i++)
{
var control= (TextBox)FindControl("text_" + (i+1));
//now you have the controls and you can do whatever you want with them
}
}
I put "Tricky" in the title because I'm aware that it will be hard to understand precisely what I want but I'll try to be clear.
I have a textBox with an event for TextChange which allow me to create the number of texboxes the user want (we will call it tChange).
Here is a part of the code for this event :
int tester;
bool flag = false;
if (!Int32.TryParse(tChange.Text, out tester))
{
flag = false;
return;
}
else
{
num = Convert.ToInt16(tChange.Text);
flag = true;
}
if (flag == true)
{
if (num >= 1)
{
for (int i = 0; i < num; i++)
{
this.Size = new Size(590, 225 + 105 * i);
textBoxesQ[i] = new TextBox();
this.Controls.Add(textBoxesQ[i]);
textBoxesQ[i].Size = new Size(45, 20);
textBoxesQ[i].Location = new Point(25, 100 + 100 * i - 1);
}
}
}
So the user enter the value and everything is OK. If he wants to change the number in the tChange, no problem too! The form is resize and the TextBoxes are created. However if he does this (change the value of tChange), everything goes wrong! Errors like
Index out of range
or I can't get the values from the TextBoxes etc..
I started thinking that the TexBoxes were created in front of the previous ones and the error came from this, so I tried to put the new ones to front, bring the old ones to front but none worked..
textBoxesQ[i].BringToFront();
textBoxesQ[i].SendToBack();
I also tried to delete the old ones before creating the new but I think that my code was wacky and it didn't work at all.
textBoxesQ[i].Dispose();
EDIT : As #Dr. Stitch said, It may come from not reinitializing the TextBoxes each time the text in tChange is changed. Now I just need to figure out how to make it happen.
You need to do three things when the number changes:
Remove any existing textboxes
Create a new array with the new size, and save a reference to that new array into your field (textBoxesQ)
Initialize the array
So something like:
if (textBoxesQ != null)
{
foreach (var textBox in textBoxesQ)
{
Controls.Remove(textBox);
}
}
textBoxesQ = new TextBox[size];
for (int i = 0; i < size; i++)
{
var textBox = new TextBox
{
Size = new Size(45, 20);
Location = new Point(25, 100 + 100 * i - 1);
};
Controls.Add(textBox);
textBoxesQ[i] = textBox;
}
I am creating a Sudoku game with ASP.NET and C#. I am required to use classes and inheritance to build the structure entirely in the code-behind page (i.e. no asp:TextBox controls on the aspx page).
I am having an awful time trying to get my inputs to clear when I start a new game. I generate a new puzzle solution, but my previous boxes don't clear and I've tried everything I can think of.
Below are several chunks of code that relate to the problem.
The code that builds the puzzle and stores it in a Puzzle object.
private Puzzle newPuzzle(int[,] solution, int numbersVisible, int maxNumbersPerBox, int maxOccurancesPerNumber)
{
Puzzle newPuzzle = new Puzzle();
SudokuTextBox newTextbox;
Number newNumber;
Random randomRC = new Random();
//variable to hold the correct answer at the given location
int answer;
//variables to hold the location within the answers array
int rowLoc;
int colLoc;
//counter to count the number of times we while loop
int counter = 0;
//variables to hold the randomly-chosen rows & col values
int row;
int col;
//array to hold the positions of the numbers we are going to show
string[] show;
show = new string[numbersVisible];
while(counter < numbersVisible)
{
//generate random numbers that gives us the location of the numbers in the solution array that we are going to show
row = randomRC.Next(0, 9);
col = randomRC.Next(0, 9);
//if the random numbers are not already in the array
if (!show.Contains(row.ToString() + ":" + col.ToString()))
{
//add them to the array
show[counter] = row.ToString() + ":" + col.ToString();
//increase the counter
counter++;
} //end if...contains
} //end while
// BUILDING THE PUZZLE
//start looping through the puzzle rows
for (int pr = 0; pr < 3; pr++)
{
//another loop for puzzle columns
for (int pc = 0; pc < 3; pc++)
{
box = new Box(); //create a new Box object
//another loop for box rows
for (int br = 0; br < 3; br++)
{
//another loop for box columns
for (int bc = 0; bc < 3; bc++)
{
newTextbox = new SudokuTextBox();
newNumber = new Number();
//grab the answer to this particular SudokuTextBox from the solutions array
rowLoc = (pr + br + (2 * pr));
colLoc = (pc + bc + (2 * pc));
answer = solution[rowLoc, colLoc];
newNumber.setNumber(answer); //set the Number to the found answer
newTextbox.setTextBoxValue(newNumber); //fill in the textbox with Number
//if this SudokuTextBox is chosen to be given at the start of the puzzle
if (show.Contains((rowLoc + ":" + colLoc).ToString()))
{
//make this SudokuTextBox visible
newTextbox.setVisibility(true);
}
else {
newTextbox.setVisibility(false);
} //end if
box.setItem(newTextbox, br, bc); //add the SudokuTextBox to the correct position inside Box
} //end box column loop
} //end box row loop
newPuzzle.setItem(box, pr, pc); //add the Box to the correct position inside Puzzle
} //end puzzle column loop
} //end puzzle row loop
return newPuzzle;
} //end easy()
Storing the new puzzle in Session:
//when the Easy button is pressed
protected void btnEasy_Click(object sender, EventArgs e)
{
//generate a new random number
Random newRandomSoln = new Random();
//keep picking new solutions until we get one that's different than the last one
do
{
solution = chooseSolution(newRandomSoln.Next(1, 11));
}
while (solution == Session["solution"]);
//store the new solution
Session["solution"] = solution;
//generate a new puzzle
Session["puzzle"] = newPuzzle( (int[,])Session["solution"], 32, 4, 4 );
}
The code that builds the table structure, fills it with the answers stored in Puzzle, and adds it to the aspx page:
////////////////////////////////
// CREATING THE PUZZLE
///////////////////////////////
Table structure = new Table(); //table to be the outer structure of the puzzle
TableRow row; //row variable to make new rows
TableCell cell; //cell variable to make new cells
Table boxTable; //table that will hold individual Boxes
TableRow boxRow; //row that will hold 3 SudokuTextBoxes
TableCell boxCell; //cell that will hold a single SudokuTextBoxes
TextBox input; //textbox that will hold the textbox in SudokuTextBox
int answer; //int to hold the answer to a particular textbox
//start looping through the puzzle rows
for (int pr = 0; pr < 3; pr++)
{
row = new TableRow(); //create a new outer row
//another loop for puzzle columns
for (int pc = 0; pc < 3; pc++)
{
cell = new TableCell(); //create a new outer cell
boxTable = new Table(); //create a new inner table
box = new Box(); //create a new Box object
box = ((Puzzle)Session["puzzle"]).getItem(pr, pc); //find the box at the current location in the puzzle
//another loop for box rows
for (int br = 0; br < 3; br++)
{
boxRow = new TableRow(); //create a new inner row
//another loop for box columns
for(int bc = 0; bc < 3; bc++)
{
boxCell = new TableCell(); //create a new inner cell
textbox = new SudokuTextBox(); //create a new SudokuTextBox object
textbox = box.getItem(br, bc); //find the SudokuTextBox at the current location in the box
//grab the answer to this particular SudokuTextBox from the solutions array
answer = ((int[,])Session["solution"])[ (pr + br + (2 * pr)), (pc + bc + (2 * pc)) ];
input = textbox.getTextBox(); //grab the textbox inside SudokuTextBox and store it
input.MaxLength = 1; //only allow 1 character to be typed into the textbox
//give the textbox an ID so we can find it later
input.ID = ("tb" + (pr + br + (2 * pr)) + "_" + (pc + bc + (2 * pc))).ToString();
boxCell.Controls.Add(input); //add the textbox to the inner cell
boxRow.Controls.Add(boxCell); //add the inner cell to the inner row
} //end box column loop
boxTable.Controls.Add(boxRow); //add the inner row to the inner table
} //end box row loop
cell.Controls.Add(boxTable); //add the inner table to the outer cell
row.Controls.Add(cell); //add the outer cell to the outer row
} //end puzzle column loop
structure.Controls.Add(row); //add the outer row to the outer table
} //end puzzle row loop
pnlPuzzle.Controls.Add(structure);
////////////////////////////////
// end puzzle
///////////////////////////////
And the SudokuTextBox class code:
public class SudokuTextBox
{
private System.Web.UI.WebControls.TextBox textbox;
private bool visible;
private Number number;
public SudokuTextBox()
{
textbox = new System.Web.UI.WebControls.TextBox();
visible = false;
number = new Number();
} //end constructor
//function to make a new textbox
public System.Web.UI.WebControls.TextBox getTextBox()
{
return textbox;
}
//function to get the value of a textbox
public Number getTextBoxValue()
{
return number;
}
//????????????
public void setTextBoxValue(Number newNumber)
{
this.number.setNumber(newNumber.getNumber());
}
//function to get the visibility of a textbox
public bool getVisibility()
{
return visible;
}
//function to change the visibility of a textbox
public void setVisibility(bool newVisible)
{
if (newVisible)
{
//if the textbox is visible
//get the number
//and make it disabled
textbox.Text = number.getNumber().ToString();
textbox.ReadOnly = true;
textbox.BackColor = System.Drawing.Color.FromArgb(150, 148, 115);
} else
{
//if it is not visible
//hide the number
//and make it enabled
textbox.ReadOnly = false;
textbox.Text = "";
textbox.BackColor = System.Drawing.Color.White;
}
}
//function to change the color of the textbox if it is wrong
public void setWrongNumber()
{
textbox.BackColor = System.Drawing.Color.FromArgb(5, 156, 202, 252);
}
//function to change the color of the textbox if it is correct
public void setCorrectNumber()
{
//but don't change disable text boxes
if(textbox.ReadOnly != true)
{
textbox.BackColor = System.Drawing.Color.White;
}
}
//function to change the color of the textbox if it is blank
public void setBlankNumber()
{
//but don't change disable text boxes
if (textbox.ReadOnly != true)
{
textbox.BackColor = System.Drawing.Color.White;
}
}
//function to show the value of a textbox when clicking the "Hint" button
//also changes the color of the textbox so we know it was shown with a hint
public void setHint()
{
setVisibility(true);
}
} //end class
Thank you to all who gave your two cents. I just wanted to let everyone know that I have solved the issue:
I ended up separating out the code that builds the table structure, taking it out of Page_Load and putting it into its own function. I then called this function from Page_Load. I also called this function when I click the "new puzzle" button. I also added similar logic to that which I commented above to clear the previous table structure before building a new one:
foreach(Control c in pnlPuzzle.Controls){
pnlPuzzle.Controls.Remove(c);
}
I'm not exactly sure why this solve my problem, but it worked!
I have list where are 6 sentences which I want to put in 6 different labels.
All six labels are named Slot0Sentence, Slot1Sentence, Slot2Sentence...
This is how I loop
for (int i = 0; i < ls.Count; i++)
{
Slot0Sentence.Text = ls[i];
}
However I dont know how to access other labels.
If there would be normal string I would do Slot + i + Sentence but in this case this dont work.
with an array of labels you can control their properties. you don't need design here, you can do that with code.
Label[] l = new Label[6];
int x = 20;
for (int i = 0; i < l.Length; i++)
{
l[i] = new Label();
l[i].Name = "Hello " + i.ToString();
l[i].Text = "Hello " + i.ToString();
l[i].Location = new Point(x, 10);
x += 100;
}
you can change the names and text to whatever you like.
I'd just use Children property of parent container (Grid, StackPanel,..). This gives you a collection which supports indexes. Additionally, in case you have different controls, use if statement
if(element in Label)
{
element.Text = ...
}
I want to insert text into textboxes creating during run time
user can decide how many textboxes will create (range 1-99) I am using this code to create textboxes
for (int i = 0; i < Calculation.Num; i++)
{
TextBox txtRun = new TextBox();
txtRun.Name = "txtBox" + i;
txtRun.Location = new System.Drawing.Point(35, 50 + (20 * i) * 2);
txtRun.Size = new System.Drawing.Size(75, 25);
this.Controls.Add(txtRun);
}
Suppose user create 5 textboxes it will look like this
after that user insert numbers in each textbox then click calculate then all numbers stored in array using this code
Button btn = sender as Button;
if (btn.Name.Equals("btn1"))
{
var sum = this.Controls.OfType<TextBox>()
.Where(t => char.IsDigit(t.Name.Reverse().Take(1).FirstOrDefault())
&& t.Enabled)
.Select(t =>
{
double i;
if (!double.TryParse(t.Text, out i)) { return 0d; }
NumbersHolder[abc] = i;
abc++;
return i;
})
.Sum();
}
after that i want to calculate those numbers if number is between 70-76 replace that number with 2.75 if it is between 77-79 replace it with 3.0 if it is between 80-86 replace with 3.3 and if it is 87-100 replace with 4.0
A little confused by what you are asking.
You want the TextBox controls you are generating in the for loop to have values?
Just set
txtRun.Text = "your value";
before adding it.