I am new to c# and need some assistance with something I am trying to do. I want to use a Color Dialog box to let the user change the color of a brush when painting a grid. I have used a button, so when it is clicked on the form, the Color Dialog loads up. However when I select a new color and then paint on the grid, the color hasn't changed. I have put the code below. Could anyone explain where I am going wrong, or what I need to do to make sure the grid is painted witht the newly selected color please.
|
J
Nilanka DharmadasaPosted Dec 17, 2009, 11:57 PM
The reason is though you set the color to the brush, you don't have access to that brush outside button click event.
So change your code as follows.
SolidBrush myBrush;//Define the varaible outside the methods.
public Form1()
{
InitializeComponent();
myBrush = new SolidBrush(Color.Black);//You set a default color as black.
pictureBox1.Paint += new PaintEventHandler(f1_paint);//Your picture box paint method
//You can write your other code here, if you want.
}
private void f1_paint(object sender, PaintEventArgs e)
{
System.Drawing.Graphics formGraphics = this.CreateGraphics();
formGraphics.FillEllipse(myBrush, 20, 20, 40, 40);
//You can write other drawing code as you like.
//But use 'myBrush ' to draw.
}
private void button2_Click(object sender, EventArgs e)
{
ColorDialog clrdlg = new ColorDialog();
if (clrdlg.ShowDialog() == DialogResult.OK)
{
myBrush = new SolidBrush(clrdlg.Color);
pictureBox1.Refresh();
}
}
If you find this answer helpful, please do not forget to check 'Do you like this answer' checkbox.
Kirtan PatelPosted Dec 17, 2009, 10:16 PM
JamesPosted Dec 17, 2009, 8:21 PM
Thaks very much for replying to my question with the code. I added this code but unfortunately it didn't work. when I click on the button, the color dialog window opens, i select a new color for the brush, paint on the grid again but the color has not changed. I also tried this code, but it didnt work.
Kind regards
Kirtan PatelPosted Dec 15, 2009, 3:32 PM
private void button1_Click(object sender, EventArgs e)
{
SolidBrush brush;
ColorDialog clrdlg = new ColorDialog();
if (clrdlg.ShowDialog() == DialogResult.OK)
{
brush = new SolidBrush(clrdlg.Color);
}
//Now use the Brush where you need
// Thats it
}