Adding a dynamically created panel to a Flowlayoutpanel on a user control - winforms

I'm working on a todo list application and I'm dynamically building a panel from another form based on user input, this said panel is suppose to be added to the flowlayoutpanel on a user control, but nothing is showing up.
Any ideas what might cause the problem.
Update: my code does work if it is executed directly from the user control itself.
My Code
private void btnCreateTask_Click_1(object sender, EventArgs e)
{
Panel pnlParentTask = new Panel();
pnlParentTask.Size = new Size(234, 89);
pnlParentTask.BorderStyle = BorderStyle.FixedSingle;
pnlParentTask.Location = new Point(217, 186);
PictureBox pbFinish = new PictureBox();
pbFinish.Size = new Size(22, 21);
pbFinish.Location = new Point(13, 13);
pbFinish.BorderStyle = BorderStyle.FixedSingle;
Label lblTitle = new Label();
lblTitle.Text = txtTaskName.Text;
lblTitle.ForeColor = Color.Black;
lblTitle.AutoSize = true;
lblTitle.Location = new Point(41, 12);
lblTitle.Font = new Font("Arial", 12f);
lblTitle.BackColor = Color.Transparent;
lblTitle.Tag = lblTitle.Text;
enc.setpanelTag(lblTitle.Text);
pnlParentTask.Tag = lblTitle.Text;
Label lblDescription = new Label();
lblDescription.Text = txtDescription.Text;
lblDescription.AutoSize = true;
lblDescription.Location = new Point(4, 38);
lblDescription.BackColor = Color.Transparent;
lblDescription.Font = new Font("Microsoft Yahei", 8.25f);
lblDescription.Tag = lblTitle.Text;
PictureBox pbPriority = new PictureBox();
pbPriority.Location = new Point(207, 3);
pbPriority.Tag = lblTitle.Text;
pbPriority.Size = new Size(22, 21);
pbPriority.BorderStyle = BorderStyle.FixedSingle;
Label lblDateCreated = new Label();
lblDateCreated.Location = new Point(3, 69);
lblDateCreated.Text = txtStartDate.Text;
lblDateCreated.BackColor = Color.Transparent;
lblDateCreated.Font = new Font("Microsoft Yahei", 8.25f);
lblDateCreated.Tag = lblTitle.Text;
Label lblDeleteTask = new Label();
lblDeleteTask.Text = "-";
lblDeleteTask.Font = new Font("Microsoft Yahei", 24f);
lblDeleteTask.Location = new Point(206, 53);
lblDeleteTask.Click += new EventHandler(lblRemoveTask_click);
pnlParentTask.Controls.Add(pbFinish);
pnlParentTask.Controls.Add(lblTitle);
pnlParentTask.Controls.Add(lblDescription);
pnlParentTask.Controls.Add(pbPriority);
pnlParentTask.Controls.Add(lblDateCreated);
pnlParentTask.Controls.Add(lblDeleteTask);
priority.flpParent.Controls.Add(pnlParentTask);
this.Close();
}

Related

How to setup and connect to database in .net 6 winform project?

I'm new to Winform (.net 6), can anyone please show me a sample code on how to set up and connect to a database (SqlServer or MySQL) in Winform? Thanks!
Here is the link to a begginers guide to accessing SQL Server through C#.
The example usage to
set up and connect to a database (SqlServer or MySQL) in Winform
I give you here:
Form1.Designer
public partial class Form1
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBox_dbAddress = new System.Windows.Forms.TextBox();
this.textBox_dbName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox_login = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.textBox_password = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(180, 88);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(132, 15);
this.label1.TabIndex = 0;
this.label1.Text = "Database server address";
this.textBox_dbAddress.Location = new System.Drawing.Point(180, 106);
this.textBox_dbAddress.Name = "textBox_dbAddress";
this.textBox_dbAddress.Size = new System.Drawing.Size(188, 23);
this.textBox_dbAddress.TabIndex = 1;
this.textBox_dbName.Location = new System.Drawing.Point(180, 153);
this.textBox_dbName.Name = "textBox_dbName";
this.textBox_dbName.Size = new System.Drawing.Size(188, 23);
this.textBox_dbName.TabIndex = 3;
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(180, 135);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(88, 15);
this.label2.TabIndex = 2;
this.label2.Text = "Database name";
this.textBox_login.Location = new System.Drawing.Point(180, 198);
this.textBox_login.Name = "textBox_login";
this.textBox_login.Size = new System.Drawing.Size(188, 23);
this.textBox_login.TabIndex = 5;
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(180, 180);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(37, 15);
this.label3.TabIndex = 4;
this.label3.Text = "Login";
this.textBox_password.Location = new System.Drawing.Point(180, 245);
this.textBox_password.Name = "textBox_password";
this.textBox_password.PasswordChar = '*';
this.textBox_password.Size = new System.Drawing.Size(188, 23);
this.textBox_password.TabIndex = 7;
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(180, 227);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(57, 15);
this.label4.TabIndex = 6;
this.label4.Text = "Password";
this.button1.Location = new System.Drawing.Point(180, 286);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 8;
this.button1.Text = "Connect";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox_password);
this.Controls.Add(this.label4);
this.Controls.Add(this.textBox_login);
this.Controls.Add(this.label3);
this.Controls.Add(this.textBox_dbName);
this.Controls.Add(this.label2);
this.Controls.Add(this.textBox_dbAddress);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label label1;
private TextBox textBox_dbAddress;
private TextBox textBox_dbName;
private Label label2;
private TextBox textBox_login;
private Label label3;
private TextBox textBox_password;
private Label label4;
private Button button1;
}
Form1
public partial class Form1 : Form
{
public Form1()
{
this.InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(
$"server={this.textBox_dbAddress.Text};" +
$"database={this.textBox_dbName.Text}; " +
$"user id={this.textBox_login.Text};" +
$"password={this.textBox_password.Text};" +
$"Trusted_Connection=yes;" +
$"connection timeout=30");
try
{
myConnection.Open();
MessageBox.Show("Connection oppened");
}
catch
{
MessageBox.Show("Connection failed");
}
finally
{
myConnection.Close();
}
}
}

Custom ContextMenu for images in a RichTextBox

Users can embed images to a RichTextBox - I add them in an InlineUIContainer.
I've added a custom ContextMenu to the InlineUIContainer, but when right-clicked
the standard RTB-contextmenu (cut, copy, paste) appears - not the custom one.
Why, and how can I fix this?
string fileName = openFileDialog.FileName;
BitmapImage bitmap = new BitmapImage(new Uri(fileName, UriKind.Absolute));
Image image = new Image();
image.Source = bitmap;
image.Width = bitmap.Width;
image.Height = bitmap.Height;
InlineUIContainer pix = new InlineUIContainer(image, rt.CaretPosition);
pix.BaselineAlignment = BaselineAlignment.Center;
pix.ContextMenu = (ContextMenu)this.Resources["imageContext"];
Right, this works - I had to recreate the all the "standard" context menu items, including the spellchecking ones (fortunately I found an example of that : )
private void rt_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
int index = 0;
MenuItem menuItem;
this.rt.ContextMenu.Items.Clear(); //Clearing the existing items
// right clicked on an image ?
int offZstart, offZend;
activeImg = null;
foreach (Block block in rt.Document.Blocks)
{
Paragraph p = block as Paragraph;
if (p != null)
{
foreach (Inline inline in p.Inlines)
{
InlineUIContainer iuic = inline as InlineUIContainer;
if (iuic != null)
{
offZstart = rt.Selection.Start.GetOffsetToPosition(iuic.ContentStart);
offZend = rt.Selection.End.GetOffsetToPosition(iuic.ContentEnd);
// if (rt.Selection.Contains(iuic.ContentStart))
if ((offZstart == 2 || offZstart == 1) && (offZend == -2 || offZend == -1))
{
if (iuic.Child is Border) // I wrap my images in borders
{
Border border = (Border)iuic.Child;
activeImg = (Image)border.Child;
MenuItem imageMenu = new MenuItem();
imageMenu.Header = "Image..";
this.rt.ContextMenu.Items.Insert(index++, imageMenu);
MenuItem borderItem = new MenuItem();
borderItem.Header = "Border";
borderItem.Click += imgBorderWidth;
imageMenu.Items.Add(borderItem);
MenuItem marginItem = new MenuItem();
marginItem.Header = "Margin";
marginItem.Click += imgMarginWidth;
imageMenu.Items.Add(marginItem);
MenuItem paddingItem = new MenuItem();
paddingItem.Header = "Padding";
paddingItem.Click += imgPaddingWidth;
imageMenu.Items.Add(paddingItem);
}
}
}
}
}
}
// spellchecking
SpellingError spellingError = this.rt.GetSpellingError(this.rt.CaretPosition);
if (spellingError != null && spellingError.Suggestions.Count() >= 1)
{
//Creating the suggestions menu items.
foreach (string suggestion in spellingError.Suggestions)
{
menuItem = new MenuItem();
menuItem.Header = suggestion;
menuItem.FontWeight = FontWeights.Bold;
menuItem.Command = EditingCommands.CorrectSpellingError;
menuItem.CommandParameter = suggestion;
menuItem.CommandTarget = this.rt;
this.rt.ContextMenu.Items.Insert(index++, menuItem);
}
//Getting the word to add/ignore
var word = this.rt.GetSpellingErrorRange(this.rt.CaretPosition);
this.rt.ContextMenu.Items.Insert(index++, new Separator());
//Adding the IgnoreAll menu item
MenuItem IgnoreAllMenuItem = new MenuItem();
IgnoreAllMenuItem.Header = "Ignore All ''"+word.Text+"''";
IgnoreAllMenuItem.Command = EditingCommands.IgnoreSpellingError;
IgnoreAllMenuItem.CommandTarget = this.rt;
this.rt.ContextMenu.Items.Insert(index++, IgnoreAllMenuItem);
this.rt.ContextMenu.Items.Insert(index++, new Separator());
//Add as new word in dictionary
MenuItem AddToDictionary = new MenuItem();
AddToDictionary.Header = "Add ''" + word.Text + "'' to dictionary";
AddToDictionary.Command = EditingCommands.IgnoreSpellingError;
AddToDictionary.CommandTarget = this.rt;
AddToDictionary.Click += (object o, RoutedEventArgs rea) =>
{
//this.AddToDictionary(word.Text);
MessageBox.Show("Want to add ''" + word.Text + "'' to dictionary\n- but don't know how..");
};
this.rt.ContextMenu.Items.Insert(index++, AddToDictionary);
this.rt.ContextMenu.Items.Insert(index++, new Separator());
}
//Cut
MenuItem cutMenuItem = new MenuItem();
cutMenuItem.Command = ApplicationCommands.Cut;
this.rt.ContextMenu.Items.Insert(index++, cutMenuItem);
//Copy
MenuItem copyMenuItem = new MenuItem();
copyMenuItem.Command = ApplicationCommands.Copy;
this.rt.ContextMenu.Items.Insert(index++, copyMenuItem);
//Paste
MenuItem pasteMenuItem = new MenuItem();
pasteMenuItem.Command = ApplicationCommands.Paste;
this.rt.ContextMenu.Items.Insert(index++, pasteMenuItem);
this.rt.ContextMenu.Items.Insert(index++, new Separator());
//Delete
MenuItem deleteMenuItem = new MenuItem();
deleteMenuItem.Command = EditingCommands.Delete;
this.rt.ContextMenu.Items.Insert(index++, deleteMenuItem);
this.rt.ContextMenu.Items.Insert(index++, new Separator());
//Select All
MenuItem selectAllMenuItem = new MenuItem();
selectAllMenuItem.Command = ApplicationCommands.SelectAll;
this.rt.ContextMenu.Items.Insert(index++, selectAllMenuItem);
}

animateLayout on expanding component is not working - codenameone

I went through the ratatouilles-restaurant code in blog. It was great. So I wanted to apply it in my app too but everything works fine except the smooth animation when the component is added. What went wrong in my code? Thankyou in advance.
protected void beforeTeamMemberTry(Form f) {
screenWidth = Display.getInstance().getDisplayWidth();
Container mainContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
f.add(mainContainer);
for (int i = 0; i < 3; i++) {
Container memberContainer = new Container(new BorderLayout());
memberContainer.getAllStyles().setMargin(5, 5, 0, 0);
mainContainer.add(memberContainer);
Label icon = new Label(theme.getImage("loginBg.png").scaledWidth(screenWidth / 9));
icon.setName("memberIcon");
zeroPaddingMargin(icon);
memberContainer.add(BorderLayout.WEST, icon);
Container detailsContainer = new Container(new BorderLayout());
Container innerContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
detailsContainer.add(BorderLayout.CENTER, innerContainer);
innerContainer.setUIID("innerclkvjd");
zeroPaddingMargin(innerContainer);
innerContainer.getAllStyles().setPadding(10, 0, 10, 0);
innerContainer.getAllStyles().setAlignment(Component.CENTER);
detailsContainer.setName("detailsContainer");
zeroPaddingMargin(detailsContainer);
detailsContainer.getAllStyles().setAlignment(Component.CENTER);
memberContainer.add(BorderLayout.CENTER, detailsContainer);
Button email = new Button("bbeck#gmai.com");
email.setName("memberEmail");
zeroPaddingMargin(email);
innerContainer.add(email);
Label position = new Label("Senior member".toUpperCase());
position.setName("memberPosition");
zeroPaddingMargin(position);
position.getAllStyles().setFgColor(0xccccc0);
position.getAllStyles().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
innerContainer.add(position);
Label emblemDown = new Label(">");
emblemDown.setUIID("emblemDown");
memberContainer.add(BorderLayout.EAST, emblemDown);
Label emblemUp = new Label("<");
emblemUp.setUIID("emblemUp");
Container descriptionContainer = new Container();
TextArea descriptionTextArea = new TextArea("slkdjfdlk dslkfdslkf jsdfksdl fksd flksd f;lsdkf sldkf sdlfk s;dl fksdl fksd flsd fkds");
descriptionContainer.add(descriptionTextArea);
descriptionTextArea.setName("memberDescription");
zeroPaddingMargin(descriptionTextArea);
descriptionTextArea.setEditable(false);
descriptionTextArea.setGrowByContent(true);
descriptionTextArea.setGrowLimit(5);
memberContainer.setLeadComponent(email);
email.addActionListener(e -> {
if (emblemDown.getParent() != null) {
memberContainer.add(BorderLayout.EAST, emblemUp);
memberContainer.add(BorderLayout.SOUTH, descriptionContainer);
memberContainer.revalidate();
} else {
memberContainer.removeComponent(emblemUp);
memberContainer.add(BorderLayout.EAST, emblemDown);
memberContainer.removeComponent(descriptionContainer);
memberContainer.revalidate();
}
memberContainer.getParent().animateLayout(300);
});
}
}
Details including phn no. (button) above in descriptionContainer but it cannot be clicked:
Container descriptionContainer = new Container();
TextArea descriptionTextArea = new TextArea("slkdjfdlk dslkfdslkf jsdfksdl fksd flksd f;lsdkf sldkf sdlfk");
descriptionContainer.add(descriptionTextArea);
descriptionTextArea.setGrowByContent(true);
descriptionTextArea.setGrowLimit(2);
Container phnContainer = new Container();
descriptionContainer.add(phnContainer);
Label phnLabel = new Label("Phn: ");
Button phn = new Button("9802921323");
phnContainer.add(phnLabel);
phnContainer.add(phn);
phn.addActionListener(e->{
System.out.println("bibek calls");
});
I have rearranged your code and change your animation code to animateLayoutAndWait(300).
Also you shouldn't call both revalidate() and animateLayout().
I also noticed that your animation was applied to the email button.
Finally, apply the animation to the right container, calling memberContainer.getParent().animateLayout(300); won't animate the emblems but the memberContainer placement.
protected void beforeTeamMemberTry(Form f) {
screenWidth = Display.getInstance().getDisplayWidth();
Container mainContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
f.add(mainContainer);
for (int i = 0; i < 3; i++) {
Container memberContainer = new Container(new BorderLayout());
memberContainer.getAllStyles().setMargin(5, 5, 0, 0);
Label icon = new Label(theme.getImage("loginBg.png").scaledWidth(screenWidth / 9));
icon.setName("memberIcon");
zeroPaddingMargin(icon);
memberContainer.add(BorderLayout.WEST, icon);
Container detailsContainer = new Container(new BorderLayout());
Container innerContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
detailsContainer.add(BorderLayout.CENTER, innerContainer);
innerContainer.setUIID("innerclkvjd");
zeroPaddingMargin(innerContainer);
innerContainer.getAllStyles().setPadding(10, 0, 10, 0);
innerContainer.getAllStyles().setAlignment(Component.CENTER);
detailsContainer.setName("detailsContainer");
zeroPaddingMargin(detailsContainer);
detailsContainer.getAllStyles().setAlignment(Component.CENTER);
memberContainer.add(BorderLayout.CENTER, detailsContainer);
Button email = new Button("bbeck#gmai.com");
email.setName("memberEmail");
zeroPaddingMargin(email);
innerContainer.add(email);
Label position = new Label("Senior member".toUpperCase());
position.setName("memberPosition");
zeroPaddingMargin(position);
position.getAllStyles().setFgColor(0xccccc0);
position.getAllStyles().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
innerContainer.add(position);
Label emblemDown = new Label(">");
emblemDown.setUIID("emblemDown");
memberContainer.add(BorderLayout.EAST, emblemDown);
Label emblemUp = new Label("<");
emblemUp.setUIID("emblemUp");
Container descriptionContainer = new Container();
TextArea descriptionTextArea = new TextArea("slkdjfdlk dslkfdslkf jsdfksdl fksd flksd f;lsdkf sldkf sdlfk s;dl fksdl fksd flsd fkds");
descriptionContainer.add(descriptionTextArea);
descriptionTextArea.setName("memberDescription");
zeroPaddingMargin(descriptionTextArea);
descriptionTextArea.setEditable(false);
descriptionTextArea.setGrowByContent(true);
descriptionTextArea.setGrowLimit(5);
memberContainer.setLeadComponent(email);
email.addActionListener(e -> {
if (emblemDown.getParent() != null) {
memberContainer.add(BorderLayout.EAST, emblemUp);
memberContainer.add(BorderLayout.SOUTH, descriptionContainer);
} else {
memberContainer.removeComponent(emblemUp);
memberContainer.add(BorderLayout.EAST, emblemDown);
memberContainer.removeComponent(descriptionContainer);
}
memberContainer.animateLayoutAndWait(300);
});
mainContainer.add(memberContainer);
mainContainer.animateLayoutAndWait(300);
}
}

Finding controls in Windows Forms C# .NET?

Using Windows Forms, two link labels are created dynamically. When the user clicks on anyone of links labels, one dynamic form is created. In that form I created one data grid, a text box and a button placed dynamically (in that dynamic form). Now I want to access the dynamic data grid in the dynamic button click event. How can I do that?
private void Users_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Usp_Get_Employees", con);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string somecode = i.ToString() + ds.Tables[0].Rows[i]["eid"].ToString();
LinkLabel lbluser = new LinkLabel();
lbluser.Name = ds.Tables[0].Rows[i]["eid"].ToString();
lbluser.Text = ds.Tables[0].Rows[i]["ename"].ToString();
lbluser.Location = new System.Drawing.Point(40, i * 40);
lbluser.Size = new System.Drawing.Size(50, 30);
Controls.Add(lbluser);
lbluser.Click += new EventHandler(lbluser_Click);
}
}
}
void lbluser_Click(object sender, EventArgs e)
{
LinkLabel lnkClis = (LinkLabel)sender;
Form frm = new Form();
frm.Name = lnkClis.Name;
frm.Text = lnkClis.Text;
frm.Show();
DataGrid dtgrd = new DataGrid();
dtgrd.Location = new System.Drawing.Point(10, 1 * 40);
dtgrd.Name = lnkClis.Name;
names = lnkClis.Name;
TextBox tx = new TextBox();
tx.Location = new System.Drawing.Point(10, 5 * 40);
tx.Size = new Size(80, 30);
tx.Multiline = true;
tx.LostFocus += new EventHandler(tx_LostFocus);
Button btn = new Button();
btn.Location = new System.Drawing.Point(10, 7 * 40);
btn.Size = new System.Drawing.Size(50, 30);
btn.Name = lnkClis.Name;
btn.Click += new EventHandler(btn_Click);
frm.Controls.Add(dtgrd);
frm.Controls.Add(tx);
frm.Controls.Add(btn);
}
// Now I am trying to access the data grid in the btn_click event
void btn_Click(object sender, EventArgs e)
{
Button btsave = (Button)sender;
string eid = btsave.Name;
object grd = btsave.Parent.Controls.Find("dtgrd", true).FirstOrDefault();
((DataGrid)grd).DataSource = ds.Tables[0];
}
Now I am getting an error object set of instances of an object at:
((DataGrid)grd).DataSource = ds.Tables[0];
The exception message you have written:
Now I am getting an error object set of instances of an object at
makes no sense, but it looks like
Object reference not set to an instance of an object
If this is the case, I think the error lays in Find method call. According to documentation:
Searches for controls by their Name property and builds an array of all the controls that match.
In your button click handler you assume that grid is called dtgrd, but while you create a grid you name it like this:
dtgrd.Name = lnkClis.Name;
it will suffice if you change this line to:
dtgrd.Name = "dtgrd";
Having said that, you should consider using an anonymous method for the button click handler. It will eliminate need for calling the Find method in the first place.
void lbluser_Click(object sender, EventArgs e)
{
//...
DataGrid dtgrd = new DataGrid();
//...
Button btn = new Button();
//...
btn.Click += (sender,args)=> dtgrd.DataSource = ds.Tables[0];
Try the following code
public Form1()
{
Form f1 = new Form();
f1.Text = "New Form";
TextBox t1 = new TextBox();
t1.Top = 0;
t1.Name = "t1";
t1.Visible = true;
f1.Controls.Add(t1);
Button b1 = new Button();
b1.Top = 30;
b1.Name = "b1";
b1.Text = "Click";
b1.Click += b1_Click;
f1.Controls.Add(b1);
f1.Show();
}
public void b1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
object txt = btn.Parent.Controls.Find("t1", false).First();
((TextBox)txt).Text = "Hi, you have clicked me.";
}
I modified Nitesh's code a bit. Just capture the textbox in the click handler using a lambda:
public Form1()
{
Form f1 = new Form();
f1.Text = "New Form";
TextBox t1 = new TextBox();
t1.Top = 0;
t1.Name = "t1";
t1.Visible = true;
f1.Controls.Add(t1);
Button b1 = new Button();
b1.Top = 30;
b1.Name = "b1";
b1.Text = "Click";
b1.Click += (sender, args) => MessageBox.Show("The text is: " + t1.Text);
f1.Controls.Add(b1);
f1.Show();
}
The error you are getting is from the statement (as the grd object is null):
((DataGrid)grd).DataSource = ds.Tables[0];
Since you are trying to catch hold of a dynamic control, it's good have a proper null checks, type checks, and error handling. Something like this:
if(grd != null && grd is DataGrid)
((DataGrid)grd).DataSource = ds.Tables[0];

Print Grid which generated dynamically in wpf

i want to print a grid which is generated dynamically.
Means, in the click event of the Print Button, i m generating a grid and then i want to print that grid.
here is my code,
private void btnPrint_Click(object sender, RoutedEventArgs e)
{
PrintDialog Objprint = new System.Windows.Controls.PrintDialog();
if (Objprint.ShowDialog() == true)
{
System.Printing.PrintCapabilities capabilities = Objprint.PrintQueue.GetPrintCapabilities(Objprint.PrintTicket);
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / this.ActualWidth, capabilities.PageImageableArea.ExtentHeight / this.ActualHeight);
#region "Make a grid For Printing"
Grid objgrid = new Grid();
objgrid.Name = "GridForPrinting";
objgrid.Width = 1000;
objgrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
objgrid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
objgrid.RowDefinitions.Add(new RowDefinition());
TextBlock objtext = new TextBlock();
objtext.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
objtext.VerticalAlignment = System.Windows.VerticalAlignment.Center;
objtext.Text = "SUPERIOR COURT OF CALIF COUNTY OF SAN BERNARDINO";
Grid.SetRow(objtext, 0);
objgrid.Children.Add(objtext);
#endregion
Objprint.PrintVisual(objgrid, "Case Summary");
}
}
this code give me blank page to print.
how can i do that?
here i get answer,
from the below code i get what i want to do...
void PrintOnClick(object sender, RoutedEventArgs args)
{
PrintDialog dlg = new PrintDialog();
if ((bool)dlg.ShowDialog().GetValueOrDefault())
{
// Create Grid panel.
Grid grid = new Grid();
// Define 5 auto-sized rows and columns.
for (int i = 0; i < 5; i++)
{
ColumnDefinition coldef = new ColumnDefinition();
coldef.Width = GridLength.Auto;
grid.ColumnDefinitions.Add(coldef);
RowDefinition rowdef = new RowDefinition();
rowdef.Height = GridLength.Auto;
grid.RowDefinitions.Add(rowdef);
}
// Give the Grid a gradient brush.
grid.Background =
new LinearGradientBrush(Colors.Black, Colors.White,
new Point(0, 0), new Point(1, 1));
// Every program needs some randomness.
Random rand = new Random();
// Fill the Grid with 25 buttons.
for (int i = 0; i < 25; i++)
{
Button btn = new Button();
btn.FontSize = 12 + rand.Next(8);
btn.Content = "Button No. " + (i + 1);
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.VerticalAlignment = VerticalAlignment.Center;
btn.Margin = new Thickness(6);
grid.Children.Add(btn);
Grid.SetRow(btn, i % 5);
Grid.SetColumn(btn, i / 5);
}
// Size the Grid.
grid.Measure(new Size(Double.PositiveInfinity,
Double.PositiveInfinity));
Size sizeGrid = grid.DesiredSize;
// Determine point for centering Grid on page.
Point ptGrid =
new Point((dlg.PrintableAreaWidth - sizeGrid.Width) / 2,
(dlg.PrintableAreaHeight - sizeGrid.Height) / 2);
// Layout pass.
grid.Arrange(new Rect(ptGrid, sizeGrid));
// Now print it.
dlg.PrintVisual(grid, Title);
}
}
The PrintVisual print a Visual object. That means, by using the PrintVisual method, we can print any control, container, Window or user control that is in the visualtree.You cannot print a control that is not in the visualtree

Resources