C# - How to Create a textbox programmatically by checked a Checkbox? - c#

I have a Form with one Button. When I click the Button, then programmatically create a Panel with one CheckBox and a TextBox; but for the TextBox the Visible is false.
If I checked the CheckBox, I want to change my TextBox to Visible = true.
Any body can help me?
public void CreateSlide(string name, string title, string desc)
{
var PanelOrder = new Panel()
{
Name = name,
Size = new Size(395, 33),
BorderStyle = BorderStyle.FixedSingle,
Location = new Point(203, 157)
};
var ckOrder = new CheckBox()
{
Name = name,
Text = "Order",
Size = new Size(102, 21),
Location = new Point(3, 5),
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 10, FontStyle.Bold)
};
ckOrder.CheckedChanged += new EventHandler(this.ckBoxOrder_CheckedChanged);
var TxtQty = new TextBox
{
Name = name,
Text = "1",
Visible = false,
BorderStyle = BorderStyle.FixedSingle,
Size = new Size(100, 25),
Location = new Point(290, 3)
};
PanelOrder.Controls.Add(ckOrder);
PanelOrder.Controls.Add(TxtQty);
}
Relevant event handler is
private void ckBoxOrder_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked == true)
{
// ??? TxtQty.Visible = true; // <- doesn't compile
}
else
{
// ??? TxtQty.Visible = false; // <- doesn't compile
}
}

You can try using lambda in order to keep all the relevant code within CreateSlide:
public void CreateSlide(string name, string title, string desc) {
var PanelOrder = new Panel() {
Name = name,
Size = new Size(395, 33),
BorderStyle = BorderStyle.FixedSingle,
Location = new Point(203, 157),
Parent = this // <- Put PanelOrder panel on the form
};
var ckOrder = new CheckBox() {
Name = name,
Text = "Order",
Size = new Size(102, 21),
Location = new Point(3, 5),
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 10, FontStyle.Bold),
Parent = PanelOrder // <- Put ckOrder on the PanelOrder panel
};
var TxtQty = new TextBox() {
Name = name,
Text = "1",
Visible = false,
BorderStyle = BorderStyle.FixedSingle,
Size = new Size(100, 25),
Location = new Point(290, 3),
Parent = PanelOrder // <- Put TxtQty on the PanelOrder panel
};
// lambda function
ckOrder.CheckedChanged += (s, e) => {
TxtQty.Visible = ckOrder.Checked;
};
}

you need to declare a variable (reference) for the textbox outside the scope of the function that creates it, then you can set it to visible true/false. alternatively (slower) you can enumerate all controls in the form (or the panel), find your text box and set it to visible true/false.

Related

C# Changing color on label doesnt work in my stacklayout

i am using code behind visual state managers to give selected labels a background color, but this doesnt work, any idea why?
var frameStackLayoutX = new StackLayout
{
Spacing = 5
};
var vsg = new VisualStateGroup() { Name = "CommonStates" };
var vs = new VisualState { Name = "Selected" };
vs.Setters.Add(new Setter
{
TargetName = "Selected",
Property = Label.BackgroundColorProperty,
Value = Colors.Red
});
vsg.States.Add(vs);
VisualStateManager.GetVisualStateGroups(frameStackLayoutX).Add(vsg);
var LabelName = new Label();
LabelName.Text = "Jhon Doe"
LabelName .WidthRequest = 100;
LabelName .Padding = new Thickness(10, 0, 0, 0);
frameStackLayoutX.Add(LabelName );
return frameStackLayoutX;
This is inside a grid, wherei use _lines.SelectedItem = pressedItem; to make sure that I can click on my label.

How to access entrys created from the xaml.cs file

I've made a void method that adds pages to my tabbed page. In this, it creates entry boxes but they are unnamed. After the person has filled in the entry boxes I want to create a report from it. How do I access the entry boxes for the information?
This is the part that adds the new entry:
grid.Children.Add(new Entry
{
AutomationId = "weerstand" + lusnummer.ToString(),
Text = "[weerstand]",
TextColor = Color.Black,
FontSize = 18,
}, 2, rownumber);
//button and bottom
Button Reportbutton = new Button
{
Text = "Report",
BackgroundColor = Color.FromHex("#093d80"),
Padding = 24,
TextColor = Color.White,
FontSize = 36,
TextTransform = TextTransform.None,
};
Reportbutton.Clicked += GenerateReport_OnClicked;
grid2.Children.Add(
Reportbutton, 0, 0);
//make page
StackLayout stacklayout1 = new StackLayout()
{
Children =
{
grid,
grid2
}
};
ScrollView pagescroll = new ScrollView()
{
Content = stacklayout1
};
ContentPage page = new ContentPage()
{
Title = "LDTB-" + number.ToString(),
Content = pagescroll
};
Children.Add(page);
}
private async void GenerateReport_OnClicked(object sender, EventArgs e)
{
//yes or no
bool answer = await DisplayAlert("Rapport", "Wilt u het rapport maken", "Yes", "No");
//Generate report
if (answer == true){
//WHAT GOES HERE TO ACCESS THE Entry?
}
}
}
You can traverse your Grid and access the value of entries in it.
You can refer the following code:
var children = grid.Children;
foreach(View child in children){
if (child is Entry) {
string value = ((Entry)child).Text;
System.Diagnostics.Debug.WriteLine("one value is = " + value);
}
}

How to save multiple dynamic textboxes value into SQL Server database

I want to add some panel dynamically into a single panel on a button click. And each dynamic panel consist of multiple text box in horizontally. And then I want to save those text box value into the database.
I have completed to add dynamic panel and horizontal multiple text box into that panel. But couldn't know how to save them into database.
Here is the code I have written:
int v = 0;
TextBox txt1;
TextBox txt2;
TextBox txt3;
TextBox txt4;
TextBox txt5;
ComboBox cmb4;
public void tett()
{
v = 0;
Panel whitePanel = new Panel();
whitePanel.Name = "wt";
// Quantity
txt1 = new TextBox();
txt1.Location = new Point(192, 38);
txt1.Size = new Size(120, 24);
txt1.Name = "text" + v ;
txt1.Text = txt1.Name;
v = v + 1;
// Total Price
txt2 = new TextBox();
txt2.Location = new Point(566, 38);
txt2.Size = new Size(120, 24);
txt2.Name = "text" + v;
txt2.Text = txt2.Name;
txt2.TextChanged += Txt2_TextChanged;
v = v + 1;
// Unit Price
txt3 = new TextBox();
txt3.Location = new Point(753, 38);
txt3.Size = new Size(120, 24);
txt3.Name = "text" + v;
txt3.Text = txt3.Name;
v = v + 1;
// Sell Price
txt4 = new TextBox();
txt4.Location = new Point(903, 38);
txt4.Size = new Size(120, 24);
txt4.Name = "text" + v;
txt4.Text = txt4.Name;
v = v + 1;
// Product
txt5 = new TextBox();
txt5.Location = new Point(5, 38);
txt5.Size = new Size(120, 24);
txt5.Name = "text" + v;
txt5.Text = txt5.Name;
txt5.AutoCompleteSource = AutoCompleteSource.CustomSource;
txt5.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txt5.MouseClick += textBox5_MouseClick;
Label lbl3 = new Label();
Label lbl4 = new Label();
Label lbl5 = new Label();
Label lbl6 = new Label();
Label lbl7 = new Label();
Label lbl8 = new Label();
lbl3.Location = new Point(5, 15);
lbl3.Text = "Product";
lbl4.Location = new Point(192, 15);
lbl4.Text = "Quantity";
lbl5.Location = new Point(379, 15);
lbl5.Text = "Unit";
lbl6.Location = new Point(566, 15);
lbl6.Text = "Total Price";
lbl7.Location = new Point(753, 15);
lbl7.Text = "Unit Purchase Price";
lbl8.Location = new Point(903, 15);
lbl8.Text = "Unit Sell Price";
cmb4 = new ComboBox();
// Unit
cmb4.Location = new Point(379, 38);
cmb4.Size = new Size(120, 24);
whitePanel.BackColor = ColorTranslator.FromHtml("#ECF0F5");
whitePanel.Location = new Point(1, a * 10);
whitePanel.Size = new Size(1330, 60);
var _button = new Button();
_button.Text = "Dispose";
_button.Name = "DisposeButton";
_button.Location = new Point(1053, 38);
_button.MouseClick += _button_MouseClick;
whitePanel.Controls.Add(_button);
a = a + 5;
v = v + 1;
whitePanel.Controls.Add(lbl3);
whitePanel.Controls.Add(lbl4);
whitePanel.Controls.Add(lbl5);
whitePanel.Controls.Add(lbl6);
whitePanel.Controls.Add(lbl7);
whitePanel.Controls.Add(lbl8);
whitePanel.Controls.Add(txt1);
whitePanel.Controls.Add(txt2);
whitePanel.Controls.Add(txt3);
whitePanel.Controls.Add(txt4);
whitePanel.Controls.Add(txt5);
whitePanel.Controls.Add(cmb4);
panel1.Controls.Add(whitePanel);
}
In this way the output is like this..... By click on the New Purchase this multiple panel with text box will appear:
Multiple dynamic panel with multiple text box
Here the way of setting text box name is not seems better way to me. I want to use an array for set the name of text boxes.
And after all I want to save those values into db by click on the save button using an array or for loop... But I don't know how to define it..
Can anyone please help me?
And thanks in advance
With this approach, a gridview is usefull.
But within your question, the approach is;
int rowNum = 1;
public void tett() {
Control[] controlsToAdd = { new TextBox(), new TextBox(), new ComboBox(), new TextBox(), new TextBox(), new TextBox(), new Button() };
string[] labels = { "Product", "Quantity", "Unit", "Total Price", "Unit Purchase", "Unit Sell Price" };
Panel whitePanel = new Panel() {
Name = "wt",
Dock = DockStyle.Top,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
AutoSize = true,
Padding = new Padding(0, 5, 0, 5),
BackColor = ColorTranslator.FromHtml("#ECF0F5")
};
int controlX = 5, controlY = 15, controlDistance = 15;
for (int i = 0; i < controlsToAdd.Length; i++) {
if (labels.Length > i) {
var label = new Label() {
Text = labels[i],
Location = new Point(controlX, controlY)
};
whitePanel.Controls.Add(label);
}
var control = controlsToAdd[i];
control.Location = new Point(controlX, controlY + 23);
control.Size = new Size(120, 24);
if (control is Button) {
control.Name = "disposeButton" + i;
control.Text = "Dispose";
control.Click += _button_MouseClick;
} else {
if(i == 0) { //if it is the Product textbox
((TextBox)control).AutoCompleteSource = AutoCompleteSource.CustomSource;
((TextBox)control).AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//control.MouseClick += textBox5_MouseClick;
}
control.Name = "Text" + i;
control.Text = "Row" + rowNum + " Text" + i;
}
whitePanel.Controls.Add(control);
controlX += 120 + controlDistance;
}
panel1.Controls.Add(whitePanel);
whitePanel.BringToFront();
rowNum++;
}
private void _button_MouseClick(object sender, EventArgs e) {
//button does its job here
((Button)sender).Parent.Parent.Controls.Remove(((Button)sender).Parent);
}
public SqlConnection Conn { get; }
void save() {
foreach(Panel whitePanel in panel1.Controls) {
var sqlString = "INSERT INTO products(productField, quantityField, unitField, priceField, purchaseField, sellPriceField) VALUES (";
foreach (Control control in whitePanel.Controls) {
if(!(control is Label) && !(control is Button)) { //So, textbox or combobox remained
sqlString += "'"+ control.Text +"', ";
}
}
sqlString = sqlString.Substring(0, sqlString.Length - 2) + ")";
//Assume you have previous construction of SqlConnection as name "Conn"
if (Conn != null) {
if (Conn.State != ConnectionState.Open) Conn.Open();
using (var cmd = new SqlCommand(sqlString, Conn)) {
cmd.ExecuteNonQuery();
}
Conn.Close();
}
Console.WriteLine(sqlString);
}
}
I have tested and works as expected. If it is not suit your needs, make me know.

Windows Forms: Extra columns in DataGridView

My DataGridView is showing extra columns. The application is a windows forms application. What could I be doing wrong?
public ConvertisForm1()
{
InitializeComponent();
openFileDialog.Filter = "Files| *.chm;*.htm;*.html;*.rtf;*.xls;*.xlsx;*.xps;*.doc;*.docx";
dataGridView.AutoGenerateColumns = false;
dataGridView.RowHeadersVisible = false;
dataGridView.ColumnCount = 5;
dataGridView.RowCount = 20;
//delete button
var deleteDataGridViewButtonColumn = new DataGridViewButtonColumn
{
HeaderText = "",
Name = deleteDataGridViewButtonColumnName,
Text = "X",
Width =20
};
dataGridView.Columns.Insert(DeleteColumnIndex, deleteDataGridViewButtonColumn);
dataGridView.Columns[FileNameAndPathColumnIndex].Width=250;
dataGridView.Columns[FileNameAndPathColumnIndex].HeaderText = "File Path";
//browse button
var browseDataGridViewButtonColumn = new DataGridViewButtonColumn
{
HeaderText = "",
Name = browseDataGridViewButtonColumnName,
Text = "...",
Width = 30
};
dataGridView.Columns.Insert(BrowseButtonColumnIndex, browseDataGridViewButtonColumn);
//convert to dropdown
var convertToDataGridViewComboBoxColumn = new DataGridViewComboBoxColumn
{
HeaderText = "Convert to",
Name = convertToDataGridViewComboBoxColumnName,
DataSource = new ArrayList { convertToComboBoxDefault, "pdf", "word"},
Width = 100,
DefaultCellStyle =
{
NullValue = convertToComboBoxDefault,
DataSourceNullValue = convertToComboBoxDefault
}
};
dataGridView.Columns.Insert(ConvertToFileTypeColumnIndex, convertToDataGridViewComboBoxColumn);
var convertDataGridViewButtonColumn = new DataGridViewButtonColumn
{
HeaderText = "",
Name = convertDataGridViewButtonColumnName,
Text = "Convert",
Width = 50
};
dataGridView.Columns.Insert(ConvertButtonColumnIndex, convertDataGridViewButtonColumn);
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
#endregion
}
have you tried DataGridView1.AutoGenerateColumns = false; ?
or you can clear all Columns before adding new Columns
see link for reference: https://stackoverflow.com/a/7430993/5694113

How to store user-controls for future editing

Can somebody help me to figure out with - how to store correctly Array of Controls added programmatically in my application?
To be more explicitly, I have a function that create programmatically some Labels and PictureBoxes, and added it to Panel Control.
var lbLip = new Label { Text = #"LIP :", Location = new Point(5, 20), Size = new Size(29, 13) };
var lbLipVar = new Label { Text = "", Location = new Point(32, 20), Size = new Size(79, 13) };
var lbRip = new Label { Text = #"RIP :", Location = new Point(5, 40), Size = new Size(31, 13) };
var lbRipVar = new Label { Text = "", Location = new Point(32, 40), Size = new Size(70, 13) };
var imgBox = new PictureBox { Image = Image.FromFile(#"data\icon\red.png"), Location = new Point(100, 40), Size = new Size(16, 11) };
var lbPid = new Label { Text = #"PID :", Location = new Point(5, 60), Size = new Size(31, 13) };
var lbPidVar = new Label { Text = "", Location = new Point(32, 60), Size = new Size(37, 13) };
var lbTime = new Label { Text = #"Time :", Location = new Point(80, 60), Size = new Size(39, 13) };
var lbTimeVar = new Label { Text = "", Location = new Point(115, 60), Size = new Size(49, 13) };
var arrayLb = new Control[9];
arrayLb[0] = lbLip;
arrayLb[1] = lbLipVar;
arrayLb[2] = lbRip;
arrayLb[3] = lbRipVar;
arrayLb[4] = imgBox;
arrayLb[5] = lbPid;
arrayLb[6] = lbPidVar;
arrayLb[7] = lbTime;
arrayLb[8] = lbTimeVar;
plObject.Controls.AddRange(arrayLb);
And now the problem is - how to store this array of Controls for the future updating (editing/removing).
Can somebody suggests a solution how to do this right?
My idea was to create a list of controls
public static List<Control> LiControls = new List<Control>();
and store in it. However I have a lots of Controls to add (~200) - and its hard to handle them all.
I would have create a seperate Serializable class with the properties you need to persist. You can save it to an xml file with the XmlSerializer and if you need to save more properties in the future, just add them to the class and the XmlSerializer will save and load the new properties properly. Good luck !

Categories

Resources