|
You can either enumerate (or iterate) over the Controls collection property which already contains your controls that are displayed on a form, or add specific control references (as Mike mentioned, not "pointers").
If you only want to deal with controls of a specific type, for instance, then you could do something like this:
foreach (Control c in Controls)
{
if (c is Button)
{
Button b = (Button)c;
b.Text = "Click me!";
}
} When you enumerate a collection, list, or any other IEnumerable implementation, do not change the underlying enumerable otherwise an exception will be thrown. If you must change the collection or list or whatever, then iterate (the ol' for loop) over the collection or list instead and update your current index accordingly.
There have been times when I wanted to keep a separate list or array (which is a static list, BTW) of certain controls in my form so I could deal with them in a loop as well. You could easily do something like this:
Control[] controls = new Control[] {
this.textBox1,
this.textBox2,
thix.button5
};
foreach (Control c in controls)
for (int i=0; i<controls.Length; i++)
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Hey all,
Just wondering if anyone out there has any insight on how to make the text in a Label go vertically, perpendicular to normal text... I can't figure it out and would sure appreciate any help!!
Tks!!!
|
|
|
|
|
You can't do it with a standard label control.
You need to use the Graphics.XXXX classes to draw text vertically.
|
|
|
|
|
you can achieve this by overriding OnPaint of System.Windows.Forms.Label .
Below code will help you in this direction.
protected override void OnPaint(PaintEventArgs e)<br />
{<br />
Graphics g=e.Graphics ;<br />
<br />
StringFormat stringFormat=new StringFormat ();<br />
stringFormat.Alignment =StringAlignment.Center ;<br />
stringFormat.Trimming =StringTrimming.None ;<br />
stringFormat.FormatFlags =StringFormatFlags.DirectionVertical ;<br />
Brush textBrush=new SolidBrush (this.ForeColor );<br />
Matrix storeState=g.Transform ;<br />
<br />
g.RotateTransform(0.0F, MatrixOrder.Append);<br />
g.TranslateTransform(100.0F, 0.0F, MatrixOrder.Append);<br />
g.DrawString (this.Text,this.Font ,textBrush,ClientRectangle ,stringFormat );<br />
g.Transform =storeState;<br />
<br />
}
Do revert back, whether you could achieve the functionality.
(tomorrow and day after tomorrow(28th and 29th) I am on leave)
Regards,
Jay.
|
|
|
|
|
Hello,
How do you append/set subitem within a row?
For example given this listview.
0 1 2 3 4 5
1 2 3 4
In row 2, I'd like to add "5" after the "4." Class ListView supports adding a new row via ListViewItem.
How do you append a new subitem to an exist row?
How do you set the entire row?
Thanks,
Kuphryn
|
|
|
|
|
Here is how I do what you are asking:
<br />
private System.Windows.Forms.ListView myList;
private System.Windows.Forms.ColumnHeader ItemNameCol;
private System.Windows.Forms.ColumnHeader SubItem1Col;<br />
private System.Windows.Forms.ColumnHeader SubItem2Col;<br />
private System.Windows.Forms.ColumnHeader SubItem3Col;<br />
<br />
ItemNameCol.Text = "Name";<br />
SubItem1Col.Text = "Col1";<br />
SubItem2Col.Text = "Col2";<br />
SubItem3Col.Text = "Col3";<br />
<br />
this.myList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[]<br />
{<br />
this.ItemNameCol,<br />
this.SubItem1Col,<br />
this.SubItem2Col,<br />
this.SubItem3Col });<br />
<br />
<br />
ListViewItem item1 = new ListViewItem("ItemName",0);<br />
item1.SubItems.Add( "SubItem1Value" );<br />
item1.SubItems.Add( "SubItem2Value" );<br />
item1.SubItems.Add( "SubItem3Value" ); <br />
<br />
myList.Items.AddRange(new ListViewItem[]{item1});
<br />
Thats how I create a new ListView. To append to a listview, I do the following:
<br />
<br />
item1.SubItems.Add( "New Item Value" );
<br />
ColumnHeader newHeader = new ColumnHeader();
newHeader.Text = "New Header";
<br />
this.myList.Columns.Add(newHeader);
<br />
I hope this helps out. The above code is quite crude, considering I wrote it pretty fast. Let me know if you have any questions about it.
|
|
|
|
|
Okay. Thanks.
Your solution works great for inserting a new column to an existing list. I was thinking more in terms of inserting (setting) text to an existing column.
0 1 2 3 4 5
1 2 3 4 <-- insert text here. column already exists.
Kuphryn
|
|
|
|
|
ListViewItem item = lstProducts.Items.Add("Column1");//<-first
item.SubItems.Add("Column2");
item.SubItems.Add("Column3");
item.SubItems.Add("Column4");
item.SubItems.Add("Column5");
easy?
and if you want to update a previously created column
listName.Items[index].SubItems[subIndex].Text = "";
|
|
|
|
|
Nice!!!
You have to love the [] operator.
Thanks,
Kuphryn
|
|
|
|
|
I used Bitmaps from camera by DirectX in my App . ( I get a frame - analyze and move to the next frame, and so on)
After a long running time I get "exception in system.drawing.dll" in the dispose.
"Object used by other process" ???
If I add "Dispose", I get it sooner.
Thank
Koby
|
|
|
|
|
Does anyone know whether using the conditional operator instead of the if...else clause has a performance hit. In VB.NET, the IIF function is 300% slower than the if...else...end if clause (according to VB.NET in a Nutshell). Also, am I correct in assuming that both true and false expressions are evaluated no matter the result of the conditional expression. For example, in the following:
a = i > j ? b - 10 : c + 20
both 'b - 10' and 'c + 20' are evaluated regardless of the result of 'i > j' (in which case, the conditional operator isn't as efficient as an if...else clause).
Thanks.
|
|
|
|
|
Anonymous wrote:
In VB.NET, the IIF function is 300% slower than the if...else...end if clause (according to VB.NET in a Nutshell).
This information is wrong, or incomplete.
IIF is implemented as a function, and as such, evals both the true and the false part and returns only the true part.
It's easy to see if you run this code:
imports Microsoft.VisualBasic
imports System
imports System.Collections
public module MyModule
function VerySlowFunc(ByVal i as integer) as integer
System.Threading.Thread.Sleep(10 * 1000)
Console.WriteLine("Veryslow called with parameter " + CStr(i))
return i * 2
end function
sub Main
Console.WriteLine(IIF(true, VerySlowFunc(1), VerySlowFunc(2)))
Console.ReadLine()
end sub
end module
This takes 20 seconds to run and print 2 messages, because VB will evaluate both the true and the false part. Change it for an if and the code will take only 10 seconds to run and print only 1 message.
Answering the question: the :? operator on C# is as fast as an if, and does not have the VB.NET behavior.
Due to technical difficulties my previous signature, "I see dumb people" will be off until further notice. Too many people were thinking I was talking about them...
|
|
|
|
|
Anonymous wrote:
In VB.NET, the IIF function is 300% slower than the if...else...end if clause
A lot of this is because VB.NET implements IIf as a function in Microsoft.VisualBasic.dll, which takes two object arguments. Therefore, if you supply integer arguments, they have to be boxed (turned into an object on the heap), then VB has to unbox the result.
The ?: operator in C# is implemented directly in the language and as such doesn't require the boxing operations.
Stability. What an interesting concept. -- Chris Maunder
|
|
|
|
|
Thanks for your replies. In hindsight, I see that I could have answered this question myself had I put a bit more thought into it. Anyway, thanks again. 
|
|
|
|
|
Hi,
I created a datagrid, bonding with a datatable, with some columns editable. If edit the fields in one row, and cursor stays in the same row,RowState is still "Unchanged", although the datatable has the new value now. RowState will be "Modified" only when I move the cursor to another row. But I want to save my changes to database without moving the cursors to other rows. How should I do it?
BTW, I use :
"if (r.RowState != DataRowState.Unchanged && r.RowState != DataRowState.Deleted)" to judge whether there are changes need to be saved. I don't want to remove this condition because it will cause a lot of unnecessary updates.
Thanks.
|
|
|
|
|
Get the CurrencyManager for the DataGrid and call EndCurrentEdit like so:
CurrencyManager cm = (CurrencyManager)dataGrid1.BindingContext[
dataGrid1.DataSource, dataGrid1.DataMember];
if (cm != null)
cm.EndCurrentEdit();
Also, use DataSet.GetChanges or DataTable.GetChanges and get the Count of rows for the tables. This is a better way of determining changes plus gives you a DataSet of just the changes so that you can pass that to your methods which update the data source (i.e., database). This will also be more efficient if you need to send this DataSet across application boundaries since it won't (potentially) require as much bandwidth since it would have fewer rows.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Thanks a lot! CurrencyManager works fine for my case.
Appreciate for your response!
|
|
|
|
|
Application Type: C# Windows Application
This application generates multiple reports in batch. For each report requested in the batch, main process spawn threads. Each thread connects to database gets DataSet and Invoke a method to attach ReportDocument with the CrystalReportViewer.
Now after threads complete execution, result is multiple reports. Even after I close all reports, I don't see the Mem Usage coming down. This looks like to be an issue with memory taken during the execution of threads.
Can somebody suggest what should be done for fast memory recovery
Thanks
Ruchi
|
|
|
|
|
|
Search your code for the instanciation of objects of classes that implement the IDisposable interface.
Most of this classes allocate unmanaged resources that are freed by calling their Dispose method, but not when they are collected by the GC.
I learned about that recently by reading a posting from Heath. Here is the linke towards our small conversation: http://www.codeproject.com/script/comments/forums.asp?msg=798736&forumid=1649#xx798384xx
|
|
|
|
|
Troschi wrote:
Most of this classes allocate unmanaged resources that are freed by calling their Dispose method, but not when they are collected by the GC.
If they're not freed at all, that's a bug in the class. Classes that allocate unmanaged resources should implement a finalizer (using the 'destructor' syntax in C#, ~ClassName ) which frees the resources.
Finalizers have a few problems in the current releases of the Framework. Firstly, the memory is only released on the second collection that hits this object. The first GC detects there are no references to this object and that it has a finalizer, so it puts the object on a finalization queue. A thread that's reserved only for calling finalizers reads this queue and calls the finalizer for each object. Once the finalizer has run, it removes the reference. The next time the GC runs for the appropriate generation (the object is considered to have survived the original collection and is promoted to the older generation) the memory will then be freed.
If you're writing your own classes, you should call GC.SuppressFinalize in your Dispose method to indicate that the object no longer requires finalization. This saves the object surviving unnecessarily.
You should still call Dispose (or use a using block) to avoid the unnecessary memory pressure caused by the implementation of finalization. Consider the finalizer to be a back-stop against failing to call Dispose .
Stability. What an interesting concept. -- Chris Maunder
|
|
|
|
|
Thanks for this explanation. I think i got the idea.
But let's go back to the pactual roblem this thread is about.
Today, i found a similar problem in my application. I have an ArrayList where i store instances of a certain class X. Each of this instances possesses a Queue that is pretty big. For example, if i add 2 instances of class X to the ArrayList the memory usage increases by 4MB.
When i remove the instances from the ArrayList, they are collected by GC (tested that) but the memory usage doesn't decrease. But also it doesn't increase when i add two new instances of class X to the ArrayList. Only a third object increases memory usage.
Could it be that the memory is freed when the instances of class X are collected by GC but somehow remains attached to my application?
|
|
|
|
|
I Want to write a program that acts like Office Tool Bar. I need to be able set the main Form to be dockable and make sure it always stays on top (adjust the main screens client area)
Possible?
Any suggestions on a starting point for
camasmartin
hobby programmer
|
|
|
|
|
depends on a) whether it should be a dll or some suchlike thing so you can import it into other things, b) how well you want it written.
do a search in these forums for things of the same subject, there was someone who took the time to write one before and explained it quite. alas i cannot remember their name.
i ended up writing my own so it could be called as a function into my stuff, and i'd know what went into it. alas i haven't yet worked out how to successfully put it into a function!
you'll need to do something like callling your code into child window, and performing some calculations to see where it is on the screen, where the parent is on the screen; and so how far they are from ech other. then, make variables like how much you want the margin to be etc. i found when you pushed it up near the edge it would flicker as it was constantly repositioning, but it was suited to that task. you're probably better looking for someone elses also, as mine only copes with parent and child mdi forms, and as yet i would have to copy and paste the code.
also, mine wouldn't snap child forms. but do post how you get on.
-------------------------------------------------------
ithium is the best.
'Science without religion is lame, religion without science is blind.' --Albert Einstein
'The pioneers of a warless world are the youth who refuse military service.' --Albert Einstein
|
|
|
|
|
Help! I am getting the following error message when trying to retrieve data using a web service in a C# app. At first before getting this error message, I was able to retrieve data at times (not changing any of the code) and then now it is only giving me this error message when trying to retrieve any of the data. Does anyone know why I am now getting this error message?
---------- Error Message -------------
An unhandled exception of type 'System.Web.Services.Protocols.SoapException' occurred in system.web.services.dll
Additional information: Server was unable to process request. --> Catastrophic failure
|
|
|
|