Lottery program with JButtons and Action Listeners - actionlistener

I want to create a lottery program.
There are supposed to be 35 numbers to choose from and you will only be able to pick 7. Therefore, I've created 35 JButtons. When you click on a JButton, it will take the value of it using Action Command and outputs the value using a JLabel.
Button number one has the value 1, button number two has the value 2 and so on.
Here is the problem though: When I click on my button, it takes the value of it (for example 12) and then it sets a JLabel to display "12". But when I click ANOTHER button after that, it CHANGES the first value instead of displaying a NEW number.
I suppose it's similar to when someone wants to use the Scanner and you use NextInt();. I basically want to be able to select another number after the first one.
Help would be appreciated since I've basically tried everything.
Thanks in advance.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Firstclass implements ActionListener {
final static String BUTTONPANEL = "Play the lottery";
final static String TEXTPANEL = "Discover nuclear physics";
final static String BUTTONPANEL2 = "Zomg free food";
final static int extraWindowWidth = 200;
final static int extraWindowHeight = 500;
//Lotto buttons
JButton b1,b2,b3,b4,b5,
b6,b7,b8,b9,b10,b11,b12,
b13,b14,b15,b16,b17,b18,
b19,b20,b21,b22,b23,b24,
b25,
b26,b27,b28,b29,b30,b31,b32
,b33,b34,b35;
//Labels
JLabel lbl1,lbl2,lbl3,lbl4,lbl5,lbl6,lbl7,info;
public void addComponentToPane(Container pane) {
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
//First panel
JPanel card1 = new JPanel() {
//Make the panel wider than it really needs, so
//the window's wide enough for the tabs to stay
//in one row.
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width += extraWindowWidth;
size.height += extraWindowHeight;
return size;
}
};
//Setting THESE particular JButtons to the first actionlistener
ActionListener FirstListener = new FirstListener();
//Adding and configuring the JButtons
b1 = new JButton(Integer.toString(1));
b1.addActionListener(FirstListener);
b1.setPreferredSize(new Dimension(50,50));
card1.add(b1);
b2 = new JButton(Integer.toString(2));
b2.addActionListener(FirstListener);
b2.setPreferredSize(new Dimension(50,50));
card1.add(b2);
b3 = new JButton(Integer.toString(3));
b3.addActionListener(FirstListener);
b3.setPreferredSize(new Dimension(50,50));
card1.add(b3);
b4 = new JButton(Integer.toString(4));
b4.addActionListener(FirstListener);
b4.setPreferredSize(new Dimension(50,50));
card1.add(b4);
b5 = new JButton(Integer.toString(5));
b5.addActionListener(FirstListener);
b5.setPreferredSize(new Dimension(50,50));
card1.add(b5);
b6 = new JButton(Integer.toString(6));
b6.addActionListener(FirstListener);
b6.setPreferredSize(new Dimension(50,50));
card1.add(b6);
b7 = new JButton(Integer.toString(7));
b7.addActionListener(FirstListener);
b7.setPreferredSize(new Dimension(50,50));
card1.add(b7);
b8 = new JButton(Integer.toString(8));
b8.addActionListener(FirstListener);
b8.setPreferredSize(new Dimension(50,50));
card1.add(b8);
b9 = new JButton(Integer.toString(9));
b9.addActionListener(FirstListener);
b9.setPreferredSize(new Dimension(50,50));
card1.add(b9);
b10 = new JButton(Integer.toString(10));
b10.addActionListener(FirstListener);
b10.setPreferredSize(new Dimension(50,50));
card1.add(b10);
b11 = new JButton(Integer.toString(11));
b11.addActionListener(FirstListener);
b11.setPreferredSize(new Dimension(50,50));
card1.add(b11);
b12 = new JButton(Integer.toString(12));
b12.addActionListener(FirstListener);
b12.setPreferredSize(new Dimension(50,50));
card1.add(b12);
b13 = new JButton(Integer.toString(13));
b13.addActionListener(FirstListener);
b13.setPreferredSize(new Dimension(50,50));
card1.add(b13);
b14 = new JButton(Integer.toString(14));
b14.addActionListener(FirstListener);
b14.setPreferredSize(new Dimension(50,50));
card1.add(b14);
b15 = new JButton(Integer.toString(15));
b15.addActionListener(FirstListener);
b15.setPreferredSize(new Dimension(50,50));
card1.add(b15);
b16 = new JButton(Integer.toString(16));
b16.addActionListener(FirstListener);
b16.setPreferredSize(new Dimension(50,50));
card1.add(b16);
b17 = new JButton(Integer.toString(17));
b17.addActionListener(FirstListener);
b17.setPreferredSize(new Dimension(50,50));
card1.add(b17);
b18 = new JButton(Integer.toString(18));
b18.addActionListener(FirstListener);
b18.setPreferredSize(new Dimension(50,50));
card1.add(b18);
b19 = new JButton(Integer.toString(19));
b19.addActionListener(FirstListener);
b19.setPreferredSize(new Dimension(50,50));
card1.add(b19);
b20 = new JButton(Integer.toString(20));
b20.addActionListener(FirstListener);
b20.setPreferredSize(new Dimension(50,50));
card1.add(b20);
b21 = new JButton(Integer.toString(21));
b21.addActionListener(FirstListener);
b21.setPreferredSize(new Dimension(50,50));
card1.add(b21);
b22 = new JButton(Integer.toString(22));
b22.addActionListener(FirstListener);
b22.setPreferredSize(new Dimension(50,50));
card1.add(b22);
b23 = new JButton(Integer.toString(23));
b23.addActionListener(FirstListener);
b23.setPreferredSize(new Dimension(50,50));
card1.add(b23);
b24 = new JButton(Integer.toString(24));
b24.addActionListener(FirstListener);
b24.setPreferredSize(new Dimension(50,50));
card1.add(b24);
b25 = new JButton(Integer.toString(25));
b25.addActionListener(FirstListener);
b25.setPreferredSize(new Dimension(50,50));
card1.add(b25);
b26 = new JButton(Integer.toString(26));
b26.addActionListener(FirstListener);
b26.setPreferredSize(new Dimension(50,50));
card1.add(b26);
b27 = new JButton(Integer.toString(27));
b27.addActionListener(FirstListener);
b27.setPreferredSize(new Dimension(50,50));
card1.add(b27);
b28 = new JButton(Integer.toString(28));
b28.addActionListener(FirstListener);
b28.setPreferredSize(new Dimension(50,50));
card1.add(b28);
b29 = new JButton(Integer.toString(29));
b29.addActionListener(FirstListener);
b29.setPreferredSize(new Dimension(50,50));
card1.add(b29);
b30 = new JButton(Integer.toString(30));
b30.addActionListener(FirstListener);
b30.setPreferredSize(new Dimension(50,50));
card1.add(b30);
b31 = new JButton(Integer.toString(31));
b31.addActionListener(FirstListener);
b31.setPreferredSize(new Dimension(50,50));
card1.add(b31);
b32 = new JButton(Integer.toString(32));
b32.addActionListener(FirstListener);
b32.setPreferredSize(new Dimension(50,50));
card1.add(b32);
b33 = new JButton(Integer.toString(33));
b33.addActionListener(FirstListener);
b33.setPreferredSize(new Dimension(50,50));
card1.add(b33);
b34 = new JButton(Integer.toString(34));
b34.addActionListener(FirstListener);
b34.setPreferredSize(new Dimension(50,50));
card1.add(b34);
b35 = new JButton(Integer.toString(35));
b35.addActionListener(FirstListener);
b35.setPreferredSize(new Dimension(50,50));
card1.add(b35);
info = new JLabel("Your numbers are: ");
card1.add(info);
lbl1 = new JLabel("");
card1.add(lbl1);
lbl2 = new JLabel("");
card1.add(lbl2);
lbl3 = new JLabel("");
card1.add(lbl3);
lbl4 = new JLabel("");
card1.add(lbl4);
lbl5 = new JLabel("");
card1.add(lbl5);
lbl6 = new JLabel("");
card1.add(lbl6);
lbl7 = new JLabel("");
card1.add(lbl7);
//Second panel
JPanel card2 = new JPanel();
card2.add(new JTextField("TextField", 20));
//Third panel
JPanel card3 = new JPanel();
card3.add(new JButton("Hardy harr"));
tabbedPane.addTab(BUTTONPANEL, card1);
tabbedPane.addTab(TEXTPANEL, card2);
tabbedPane.addTab(BUTTONPANEL2, card3);
pane.add(tabbedPane, BorderLayout.CENTER);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Slutuppgift");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Firstclass demo = new Firstclass();
demo.addComponentToPane(frame.getContentPane());
//Display the window.
//frame.pack();
frame.setVisible(true);
frame.setSize(500,700);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private class FirstListener implements ActionListener {
/** This method will be invoked when a button is clicked */
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1 || e.getSource()==b2 || e.getSource()==b3||
e.getSource()==b4 || e.getSource()==b5 || e.getSource()==b6 ||
e.getSource()==b7 || e.getSource()==b8 ||
e.getSource()==b9 || e.getSource()==b10 ||
e.getSource()==b11 || e.getSource()==b12 || e.getSource()==b13 ||
e.getSource()==b14 || e.getSource()==b15 || e.getSource()==b16 ||
e.getSource()==b17 || e.getSource()==b18 || e.getSource()==b19 ||
e.getSource()==b20 || e.getSource()==b21 || e.getSource()==b22 ||
e.getSource()==b23 || e.getSource()==b24 || e.getSource()==b25 ||
e.getSource()==b26 || e.getSource()==b27 || e.getSource()==b28 ||
e.getSource()==b29 || e.getSource()==b30 || e.getSource()==b31 ||
e.getSource()==b32 || e.getSource()==b33 || e.getSource()==b34 ||
e.getSource()==b35) {lbl1.setText(e.getActionCommand());}
}
}
private class SecondListener implements ActionListener {
public void actionPerformed(ActionEvent d) {
if (d.getSource() == b1 || d.getSource()==b2 || d.getSource()==b3||
d.getSource()==b4 || d.getSource()==b5 || d.getSource()==b6 ||
d.getSource()==b7 || d.getSource()==b8 ||
d.getSource()==b9 || d.getSource()==b10 ||
d.getSource()==b11 || d.getSource()==b12 || d.getSource()==b13 ||
d.getSource()==b14 || d.getSource()==b15 || d.getSource()==b16 ||
d.getSource()==b17 || d.getSource()==b18 || d.getSource()==b19 ||
d.getSource()==b20 || d.getSource()==b21 || d.getSource()==b22 ||
d.getSource()==b23 || d.getSource()==b24 || d.getSource()==b25 ||
d.getSource()==b26 || d.getSource()==b27 || d.getSource()==b28 ||
d.getSource()==b29 || d.getSource()==b30 || d.getSource()==b31 ||
d.getSource()==b32 || d.getSource()==b33 || d.getSource()==b34 ||
d.getSource()==b35) {lbl2.setText(d.getActionCommand());}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}`

Your listener needs to know which label to change. Learn how to use arrays and then your code can be something like (pseudo code)
int labelToChange = 0;
JLabel labels[];
listener()
{
// This is actually bad: using the GUI as the "source" of data
// but in this case there are so many other issues this is the least
// of your problems...
//
if (labelToChange < 7) {
labels[labelToChange++] = e.getSource().getText();
} else {
// ERROR - too many buttons pressed
}
}
}

Related

Trouble changing background color of row in codename one table

I have an app with a route datatable. The data is csv file. I like
highlight a row in a table in codenameone by changing the backgroundcolor of the row. How can I do this?
My Code is
String File_Name ="/route.csv";
//"/root/sdcard/Pictures/route.csv";
File f= new File (File_Name);
if (f.exists())
InputStream is = Display.getInstance().getResourceAsStream(getClass(), File_Name );
CSVParser parser = new CSVParser();
String[][] data = parser.parse(is);
String[] columnNames = new String[data[0].length];
l = data.length;
for(int iter= 0 ; iter < columnNames.length ; iter++) {
if (iter== 0) {
columnNames[iter] = "Naam";
}
else if (iter== 1) {
columnNames[iter] = "Latitude";
}
else if (iter== 2) {
columnNames[iter] = "Longitude";
}
}
tm = new DefaultTableModel(columnNames, data);
}
}
catch (IOException err){
err.printStackTrace();
}
further in the code
Table tm2 = new Table(tm)
EDIT solved myself
I edited the table definiton tm2 and added the variable A. A is the row which is highlighted
Table tm2 = new Table(tm) {
#Override
public Component createCell(Object value, int row, int column, boolean editable) { // (1)
Component cell;
cell = super.createCell(value, row, column, editable);
if(row > a-1 && row < a+1) { // (5)
// pinstripe effect
cell.getAllStyles().setBgColor(0xe2f30d);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}
Changing the cell color is discussed in the developer guide as you probably discovered the pinstripe sample from there.
The full sample from the developer guide is this:
Table table = new Table(model) {
#Override
protected Component createCell(Object value, int row, int column, boolean editable) {
Component cell;
if(row == 1 && column == 1) {
Picker p = new Picker();
p.setType(Display.PICKER_TYPE_STRINGS);
p.setStrings("Row B can now stretch", "This is a good value", "So Is This", "Better than text field");
p.setSelectedString((String)value);
p.setUIID("TableCell");
p.addActionListener((e) -> getModel().setValueAt(row, column, p.getSelectedString()));
cell = p;
} else {
cell = super.createCell(value, row, column, editable);
}
if(row > -1 && row % 2 == 0) {
// pinstripe effect
cell.getAllStyles().setBgColor(0xeeeeee);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}
#Override
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
TableLayout.Constraint con = super.createCellConstraint(value, row, column);
if(row == 1 && column == 1) {
con.setHorizontalSpan(2);
}
con.setWidthPercentage(33);
return con;
}
};

Activate Progress Bar outside the main using data claculating in the background

i'm trying to activate progress bar that showing the advance of the "for loop" i have while i reading my files and writes them to excel file.
the problam is that the bar don't update to the user until the end of the for loop in each way i tried. what is the right way to do this? is it possible to activate progress bar in the middle of the MyPanel class?
i have the next classes:
Tester(contain the main) , MyPanel , LogFileReader , DefectFileReader.
Tester
public class Tester {
public static void main(String[] args){
JFrame frame = new JFrame("Analayzer GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 300);
frame.setLocationRelativeTo(null);
MyPanel p = new MyPanel();
frame.add(p);
frame.setVisible(true);
}
}
My Panel (only the relevant code)
public class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
/*...........(code irelevant).......*/
if(click.getSource() == analayze){
Boolean valid = isValidToStart();
if(valid == true){
try{
fos = new FileOutputStream("c:/temp/analayze.xlsx");
if(DFloaded == true){
try {
pbar.repaint();
DF = new File[DFLIST.length];
dfReader = new DefectFileReader[DFLIST.length];
docArray = new Document[DFLIST.length];
for(int i = 0 ; i < DFLIST.length ; i++){
/******* This is where i want to update my bar according to (i/DFList.length) ********/
System.out.println("i'm sending the file down here to parse from file to document");
System.out.println(DFLIST[i].getAbsoluteFile());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
docArray[i] = (Document) db.parse(DFLIST[i]);
docArray[i].getDocumentElement().normalize();
dfReader[i] = new DefectFileReader(DFLIST[i] , docArray[i]);
dfReader[i].getRunsIndex();
totalDuration = sumTimes(dfReader[i].inspectionDuration());
if(i==0){
firstWriteToExcel(dfReader[0], sheet, workbook, fos);
writeToExcel(dfReader[0], sheet, workbook, fos);
}
if(i!=0)
writeToExcel(dfReader[i] , sheet , workbook , fos );
repaint();
if(INPloaded == true){
}
DFLIST[i] = null;
dfReader[i].clearDfReader();
docArray[i] = null;
System.gc();
}
}
catch(Exception e ) {
System.out.println(e);
System.exit(0);
}
}
row = sheet.createRow(rowIndex);
totalDuration = sumTimes("00:00:00");
if(inspectionDuration.getState() == true){
row.createCell(cellIndex - 1).setCellValue(totalDuration);
row.getCell(cellIndex - 1).setCellStyle(csForFirstWrite);
}
((Workbook) workbook).write(fos);
workbook.close();
JOptionPane.showMessageDialog(null, "Your data has been analyze!\n you can find the result in c:\\temp");
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
}

Drag and drop JLabel while preserving the original JLabel

I am working on a GUI that displays an image of a floor plan (JLabel with ImageIcon) and a number of small icons (JLabels with ImageIcon) down the left hand side. The idea is to be able to select one of the icons and drag and drop it onto a position on the floor plan. My code is working fine except that when you drag an icon onto the floor plan, I need the original icon to remain in place, so it can be placed in several other positions on the floor plan if required. So I need to be able to clone the icon that I am moving when the mouse is pressed.
My code below shows a temp fix between the //******** markers but of course this only works correctly for the topmost icon. I need to somehow clone "Component comp" as a new JLabel.
Below is the relevant part of my code:
class MouseHandler extends MouseAdapter {
private Component dragComponent;
private Sidebar board;
private Point dragOffset;
public MouseHandler(Sidebar board) {
this.board = board;
}
public Sidebar getBoard() {
return board;
}
#Override
public void mousePressed(MouseEvent e) {
Component comp = getBoard().getComponentAt(e.getPoint());
if (comp != null) {
if (comp instanceof JLabel) {
//**************
String imagePath = "/Downlight 1.gif";
Image Images = new ImageIcon(this.getClass().getResource(imagePath)).getImage();
String path = "Images" + imagePath;
ImageIcon icon = new ImageIcon(path);
JLabel lbl = new JLabel(icon);
lbl.setBounds(22, 26, 36, 36);
lbl.setIcon(new ImageIcon(Images));
lbl.setOpaque(true);
Sidebar board = getBoard();
board.add(lbl, new Point(40, 44));
board.setComponentZOrder(lbl, 0);
//**************
dragComponent = comp;
dragOffset = new Point();
dragOffset.x = e.getPoint().x - comp.getX();
dragOffset.y = e.getPoint().y - comp.getY();
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (dragComponent != null) {
board = getBoard();
Point dragPoint = new Point();
dragPoint.x = e.getPoint().x - dragOffset.x;
dragPoint.y = e.getPoint().y - dragOffset.y;
dragComponent.setLocation(dragPoint);
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (dragComponent != null) {
dragComponent = null;
}
}
}
}
Thanks in advance for any help with this.
I found a solution that enabled me to copy the icon and bounds of the original JLabel to a new JLabel, which replaces the one being dragged:
#Override
public void mousePressed(MouseEvent e) {
Component comp = getBoard().getComponentAt(e.getPoint());
if (comp != null) {
if (comp instanceof JLabel) {
JLabel label = (JLabel) comp;
ImageIcon icon = ((ImageIcon)label.getIcon());
Rectangle rect = label.getBounds();
JLabel lbl = new JLabel(icon);
lbl.setBounds(rect);
lbl.setVisible(true);;
lbl.setOpaque(true);
Mainpanel board = getBoard();
board.add(lbl);
board.setComponentZOrder(lbl, 0);
dragComponent = comp;
dragOffset = new Point();
dragOffset.x = e.getPoint().x - comp.getX();
dragOffset.y = e.getPoint().y - comp.getY();
}
}
}

Changing colors in xamDataGrid cells

I have xamDataGrid bound to DataTable where first column contains reference values. Coloring of all other columns depends on whether the value in cells is or isn't equal to the value of reference column. The logic uses converter.
What I want to achieve is when I move another column to the 1st position, it will become the reference column and the colors in all other columns should change.
I'm listening to FieldPositionChanged event and invalidating the grid layout, but it does not work:
grid.UpdateLayout();
grid.InvalidateVisual();
The breakpoint in converter is hit but not for all records (only 2 or 3).
If you set the CellValuePresenterStyle when the fields move they should update correctly. The following logic will do this:
void XamDataGrid1_FieldPositionChanged(object sender, Infragistics.Windows.DataPresenter.Events.FieldPositionChangedEventArgs e)
{
FieldLayout layout = e.Field.Owner;
Field first = null;
foreach (Field f in layout.Fields)
{
if (f.ActualPosition.Column == 0)
first = f;
}
if (first != null)
{
SetCellValuePresenterStyle(e.Field.Owner, first);
}
}
void XamDataGrid1_FieldLayoutInitialized(object sender, Infragistics.Windows.DataPresenter.Events.FieldLayoutInitializedEventArgs e)
{
SetCellValuePresenterStyle(e.FieldLayout, e.FieldLayout.Fields[0]);
}
void SetCellValuePresenterStyle(FieldLayout layout, Field sourceField)
{
Binding sourceValueBinding = new Binding("DataItem[" + sourceField.Name + "]");
foreach (Field f in layout.Fields)
{
if (f != sourceField)
{
Style cellValuePresenterStyle = new Style(typeof(CellValuePresenter));
Binding compareValueBinding = new Binding("DataItem[" + f.Name + "]");
MultiBinding styleBinding = new MultiBinding();
styleBinding.Bindings.Add(sourceValueBinding);
styleBinding.Bindings.Add(compareValueBinding);
styleBinding.Converter = new EqualMultiValueConverter();
DataTrigger trigger = new DataTrigger();
trigger.Value = true;
trigger.Binding = styleBinding;
cellValuePresenterStyle.Triggers.Add(trigger);
Setter backgroundSetter = new Setter(Control.BackgroundProperty, Brushes.Green);
trigger.Setters.Add(backgroundSetter);
f.Settings.CellValuePresenterStyle = cellValuePresenterStyle;
}
else
{
f.Settings.CellValuePresenterStyle = null;
}
}
}

How can i refer to a textbox that i don't know it's name?

I'm using VC++ 2008 (Windows Form Application C++\CLR), I created dynamic array of textboxes (the user defines how many textboxes he wants to create), and i want to make a KeyPress event handler, in order to prevent Chars (i want these textboxes to be numerical only, and accept only one dot "for decimal numbers"). So how can I refer to the textbox that the user is using (the textbox that the cursor on for example) is there any way i can do this? The function looks like:
private: System::Void textBox_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
if(e->KeyChar == '.')
{
if(this->/*the textbox in use*/->Text->Contains(".") && !this->/*the textbox in use*/->SelectedText->Contains("."))
e->Handled = true;
}
else if(!Char::IsDigit(e->KeyChar) && e->KeyChar != 0x08)
e->Handled = true;
}
private void CreateTextBoxControls()
{
intColCount= Convert.ToInt32(txtColumnNo.Text.ToString().Trim());
int rowCount =0;
Table tblHead = new Table();
if (tblHead.GetType().ToString().Equals("System.Web.UI.WebControls.Table") && PHOptions.FindControl("tblHead") == null )
{
tblHead.ID = "tblHead";
tblHead.EnableViewState = true;
tblHead.BorderWidth=Unit.Pixel(0);
tblHead.CellSpacing = 0;
tblHead.CellPadding = 1;
tblHead.Width = Unit.Percentage(96);
TableRow rH = new TableRow();
TableCell cH = new TableCell();
cH.Text= "Table Heading" ;
cH.Font.Bold = true;
rH.Cells.Add(cH);
tblHead.Rows.Add(rH);
PHOptions.Controls.Add(tblHead);
if(intColCount>0)
rH.Visible =true;
else
rH.Visible =false;
}
Table tblHelp = new Table();
if (tblHelp.GetType().ToString().Equals("System.Web.UI.WebControls.Table") && PHOptions.FindControl("tblHelp") == null )
{
tblHelp.ID = "tblHelp";
}
tblHelp.EnableViewState = true;
tblHelp.BorderWidth=Unit.Pixel(1);
tblHelp.CellSpacing = 0;
tblHelp.CellPadding = 1;
tblHelp.BorderWidth = Unit.Pixel(1);
tblHelp.Width = Unit.Percentage(96);
for (int rowIndex=0; rowIndex<=rowCount; rowIndex++)
{
TableRow r = new TableRow();
TableRow rWeight= new TableRow();
//r.ID = "rLabel";
TableRow rID = new TableRow();
for (int clIndex=0; clIndex<intColCount; clIndex++)
{
TableCell c = new TableCell();
txtBox = new TextBox();
if (txtBox.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox") && PHOptions.FindControl("txtOption"+(clIndex+1).ToString()) == null )
{
txtBox.ID ="txtOption"+(clIndex+1).ToString();
//txtBox.Text = (clIndex+1).ToString();
txtBox.Width= Unit.Pixel(45);
txtBox.MaxLength = 2;
c.BorderWidth=Unit.Pixel(1);
c.Width=Unit.Pixel(80);
c.Controls.Add(txtBox);
r.Cells.Add(c);
txtBox.PreRender += new System.EventHandler(this.txtBox_PreRender);
}
}
tblHelp.Rows.Add(r);
}
TableRow rSubmit = new TableRow();
TableCell cSubmit = new TableCell();
cSubmit.ColumnSpan = intColCount ;
btnSubmitButton = new Button();
btnSubmitButton.ID ="btnSubmit";
btnSubmitButton.Text= "Submit";
if( PHOptions.FindControl("btnSubmit") == null )
cSubmit.Controls.Add(btnSubmitButton);
cSubmit.Attributes.Add("Align","Center");
rSubmit.Cells.Add(cSubmit);
tblHelp.Rows.Add(rSubmit);
PHOptions.Controls.Add(tblHelp);
this.btnSubmitButton.PreRender += new System.EventHandler(this.btnSubmitButton_PreRender);
this.btnSubmitButton.Click += new System.EventHandler(this.btnSubmitButton_Click);
}
private void btnSubmitButton_Click(object sender, System.EventArgs e)
{
for (int clIndex=0; clIndex<intColCount; clIndex++)
{
string boxName = "txtOption" + (clIndex+1).ToString();
TextBox tb = PHOptions.FindControl(boxName) as TextBox;
if( lblDisplay.Text != "" )
lblDisplay.Text+=","+tb.Text ;
else
lblDisplay.Text=tb.Text ;
}
}
Just refer this code ...
(this contains both for creating textbox dynamically and read from textbox)

Resources