|
Hello. I create some panels (on another panel) dynamically and store them in an array. Following is the code for it
m_panels[nCount] = new Panel();
panel1.Controls.Add(m_panels[nCount]);
m_panels[nCount].BackColor = Color.Red;
m_panels[nCount].Location = e.Location;
m_panels[nCount].Size = new System.Drawing.Size(12, 12);
m_panels[nCount].Visible = true;
Following is the code I use for deleting them
for (int i = 0; i < m_panels.Length; i++)
{
if (m_panels[i] != null)
{
panel1.Controls.Remove(m_panels[i]);
m_panels[i].Dispose();
}
}
When I delete the panels, they should be deleted from the array. Instead, I can see them when I add new panels dynamically. Whats wrong here? Thanks for any input.
|
|
|
|
|
You aren't deleting them from the array - you are just deleting (or rather Disposing) the instance - the value in the array doesn't change because the instance it references no longer exists.
Try this:
for (int i = 0; i < m_panels.Length; i++)
{
if (m_panels[i] != null)
{
panel1.Controls.Remove(m_panels[i]);
m_panels[i].Dispose();
m_panels[i] = null;
}
}
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
One of the best arguments for using Generic Lists is that you do not have to deal with explicit re-sizing, and there is no effective way to remove a value from an Array except by re-sizing. Note that it wasn't until .NET FrameWork 3.5 that we had an Array 'Resize method, and that multi-dimensional Arrays cannot be re-sized.
If you re-use the same Array, and add more elements (Panels) in any given re-use, then your Array is going to grow in size, possibly, become "cluttered" as you re-use it.
List<Panel> m_panels = new List<Panel>();
Panel newPanel = new Panel();
newPanel.Name = "panel m_" + i.ToString();
newPanel.BackColor = Color.Red;
newPanel.Location = e.Location;
newPanel.Size = new System.Drawing.Size(12, 12);
newPanel.Visible = true;
m_panels.Add(newPanel);
panel1.Controls.Add(newPanel);
for (int i = 0; i < m_panels.Count; i++)
{
Panel panelToRemove = m_panels[i];
if (panel1.Controls.Contains(panelToRemove))
{
panel1.Controls.Remove(panelToRemove);
}
else
{
throw new MissingMemberException(
string.Format("Panel: {0} in source list of Panels not in panel1.Controls",
panelToRemove.Name));
}
}
m_panels.Clear()
«If you search in Google for 'no-one ever got fired for buying IBM:' the top-hit is the Wikipedia article on 'Fear, uncertainty and doubt'» What does that tell you about sanity in these times?
modified 26-Nov-14 16:23pm.
|
|
|
|
|
Hello all,
I have a little problem.
I have a picture on a WPF window and I would like to update it,when an event is fired(the event is fired after the picture file is update).
The code below,is in the callback of the event,and work only the first time,after the second time is fired the picture visualization is not updated(that means that the displayed picture does not change but the file BMP is overwrited correctly in the folder).
if (File.Exists(@"C:\\Temp\\LivePictures\\pic.BMP"))
{
Dispatcher.Invoke((Action)(() =>
{
BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.UriSource = new Uri(@"C:\\Temp\\LivePictures\\pic.BMP");
bmi.CacheOption = BitmapCacheOption.OnLoad;
bmi.EndInit();
imgOrientation.Source = bmi;
}));
}
Any suggestion?
Any help is appreciated
Thanks
|
|
|
|
|
Have you tried to use a Stream as resource?
I use a method for converting System.Drawing.Image to BitmapImage and display it.
/// <summary>
/// WPF convert System.Drawing.Image to System.Windows.Media.Imaging.BitmapImage
/// </summary>
/// <param name="img">Image to convert</param>
/// <returns>Converted image</returns>
public static System.Windows.Media.Imaging.BitmapImage ImageToBitmapImage(System.Drawing.Image img)
{
System.Windows.Media.Imaging.BitmapImage bitmap = new System.Windows.Media.Imaging.BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
bitmap.BeginInit();
bitmap.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
bitmap.StreamSource = ms;
bitmap.EndInit();
}
return bitmap;
}
Set the WPF Image like this:
imgMain.Source = ImageHelpers.ImageToBitmapImage(img);
I use this method (and others) to manipulate images at runtime and does it's job
Maybe you encounter this problem because of the way "UriSource" is updating it's stuff ... dunno
Greet$
|
|
|
|
|
I have a form in which I have a field date of birth , and a textbox to fill date of birth. When a person fills his date of birth like 01/01/1990, then it will be saved into database and when I retrieve this date form database then this comes 01/01/1990 12:00 AM. I want only date part from it.
This is my form to fillup date of birth
form.aspx
<tr>
<td width="30%">
Date of Birth
<br />
</td> <td style="width: 1px">
:<asp:TextBox ID="txtDateofBirth" runat="server" placeholder="dd/mm/yyyy"></asp:TextBox>
</td> <td class="td2">
</td>
</tr>
This is code for form.aspx.cs
SqlCommand cmd = new SqlCommand("insert into ApplicantForm(NameofApplicant, dateofbirth)" +
"values( @NameofApplicant, convert(Datetime, @dateofBirth, 103)", con);
cmd.Parameters.AddWithValue("@dateofBirth",txtDateofBirth.Text); This is code for print of this date of birth
print.aspx
<asp:Label ID="txtDOB" runat="server" ></asp:Label> This is code print.aspx.cs
SqlCommand cmd = new SqlCommand("Select * from ApplicantForm Where ApplicantId=" + ((Request.QueryString["ApplicantId"])) + "", con);
dr = cmd.ExecuteReader();
txtDOB.Text = dr["dob"].ToString();
modified 26-Nov-14 1:17am.
|
|
|
|
|
Try something like this:
txtDOB.Text = dr["dob"].ToString("d"); This is the culture agnostic short format date specifier. What this does is print the date only in a format that is appropriate to the culture.
|
|
|
|
|
Member 11264479 wrote: SqlCommand cmd = new SqlCommand("Select * from ApplicantForm Where ApplicantId=" + ((Request.QueryString["ApplicantId"])) + "", con);
This code is vulnerable to SQL Injection[^].
NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
using (SqlCommand cmd = new SqlCommand("SELECT dob FROM ApplicantForm WHERE ApplicantId = @ApplicantId", con))
{
cmd.Parameters.AddWithValue("@ApplicantId", Request.QueryString["ApplicantId"]);
object dob = cmd.ExecuteScalar();
if (dob != null && !Convert.IsDBNull(dob))
{
txtDOB.Text = string.Format("{0:d}", dob);
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I have been developing C# applications for desktops and will like to develop a windows mobile 6.5 apps using VS2013 C#, is this possible and how do I get set up for it? I read some old post and VS2008 seems to be the platform. Looking forward to an answer.
Thanks
Ron
modified 25-Nov-14 14:36pm.
|
|
|
|
|
|
|
private void button1_Click(object sender, EventArgs e)
{
Thread th = new Thread(run);
th.Start();
run();
}
public void run()
{
for (int i = 0; i < 2; i++)
{
textBox1.Text = "I is now " + i;
Thread.Sleep(100);
}
} Could you please tell me what is wrong with this code? It's throwing System.InvalidOperationException on the line
textBox1.Text = ...
modified 25-Nov-14 8:28am.
|
|
|
|
|
1) Not in preformatted block;
2) Which line triggers the error?
Anyway the main problem I think is in Thread.Slepp(100).
Thread is the name of the class, not of the instance. The instance is thrown away at the end of button_1.click() beacuse it goes out of scope, so you'd probably want to pass its reference to the thread procedure OR declare it as a static class variable.
|
|
|
|
|
In additional information section its saying that " Control 'textBox1' accessed from a thread other than the thread it was created on".
|
|
|
|
|
The error is precisely what it states: you cannot directly access a control from a different thread. A quick search on Google drove me here[^], where there are links to msdn, codeproject and stockoverflow articles explaining the matter in more detail.
|
|
|
|
|
Accessing controls from another thread than where they where created is prohibited and you need to work around this by using delegates.
Please note that doing something like this is very resource heavy and should be avoided if possible.
Example of how you can do this. If you need to update multiple GUI components make sure you update them all at once as you only need to invoke once.
private void button1_Click(object sender, EventArgs e) {
Thread th = new Thread(run);
th.Start();
run();
}
public void run() {
for (int i = 0; i < 2; i++) {
UpdateTextBox("I is now " + i);
Thread.Sleep(100);
}
}
private delegate void DUpdateTextBox(string text);
private void UpdateTextBox(string text) {
if (textBox1.InvokeRequired) {
var d = new DUpdateTextBox(UpdateTextBox);
textBox1.Invoke(d, text);
} else {
textBox1.Text = text;
}
}
|
|
|
|
|
Thanks above code is get worked..
|
|
|
|
|
den2k88 wrote: Thread is the name of the class, not of the instance. It's a static method, so no problem there.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
You are accessing the UI (textBox1) from a different thread than the one it was created on; that's not allowed. You'd want to invoke that (Google for the invoke pattern on MSDN).
It is also starting the run-method on the main-thread, after starting it on a separate thread. Meaning it would be running twice.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
You are using a thread to access a textbox on a different thread. To solve this you will need to create a delegate to access the textbox.
have a read of this invoke textbox from thread[^]
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
You can't access UI objects (i.e. controls) except from the UI thread.
So when you try to change the Text property of your textbox from the run method, it fails because it is being executed on the th thread instead.
If you need to access UI controls, you will have to Invoke them first in order to move execution back to the thread that created them: MSDN Invoke[^]
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Beyond the cross-threading issue pointed out in other posts here, let me warn you about one thing: you have the run function running twice - in different threads at the same time, and it is not thread-safe at all.
|
|
|
|
|
public FormType() {
button.Cick += (o, e) => {
Task.Factory.StartNew(() => {
for (var i = 0; i < 2; i++) {
textBox.Invoke((Action)delegate {
textBox.Text = string.Format("Variable i currently set to: {0}", i);
});
Thread.Sleep(100);
}
});
}
}
|
|
|
|
|
the issue is (probably) that you call UI elements off the main thread. This is not allowed.
You´ll need to "invoke" a method from the thread which will set the Text.
hope this helps.
|
|
|
|
|
Hi ,
Need clarity regarding the custom sections in the app.Config file.
If the section type is System.Configuration.ConfigurationSectionCollection, how should this be coded in C#?
I did some browsing and found that
The type attribute, which is the name of the class that reads the information.
A sample of the app.config file :
="1.0"="utf-8"
<configuration>
<configSections>
<Section name="ClientSettings" type="System.Configuration.ConfigurationSectionCollection" />
</configSections>
<appSettings>
<add key="ServiceName" value="XXX Server A" />
<add key="LogfileName" value="XXXServer.log" />
<add key="LogfileFolder" value="C:\Program Files\XXXServer\logfiles\" />
</appSettings>
<ClientSettings>
<add key="Port1" value="12345" />
<add key="Port2" value="67899" />
</ClientSettings>
</configuration>
How should this be coded in C# ? Anyone kindly help me out.
Some links would also be helpful.
Thanks in advance .
|
|
|
|