|
Well, you don't have to call it after you finish with the object. That is if you don't mind unmanaged resources being left unfreed. In most cases, the Dispose method is there for your application to tell the underlying code to dispose of unmanaged resources - there are exceptions where people are doing odd behaviour in the Dispose (such as closing a database connection - odd yes, but I have seen it), but it is good practice to Dispose of resources when you've finished with them.
In your example, you can do
using (Pen pen = new Pen)
{
} and the Dispose method is automatically called for you because the using (){} essentially converts into a try/finally block where the finally calls the Dispose method.
|
|
|
|
|
Always call Dispose transitively - in your Dispose override, call Dispose (or Close) on any resources that your class was holding on to. Yes, finalization is there as a backstop - but it's such a bad one, you never want your code to end up in the finalizer.
Database connections are a special case. Because the provider is normally pooling connections for you, it's more acquire/release than create/destroy. Best Practice is to acquire a connection just before executing an operation and release it just after. Don't go over the top, if you have a set of causally-related database activities you can execute them all on the same connection, but generally you should be using a using block with any connection you create.
DoEvents: Generating unexpected recursion since 1991
|
|
|
|
|
Now I'm very clear. Thanks all.
|
|
|
|
|
Hello
I have an excel file which contain some titles and dateand....
and a row that look like this:
Name Director Signature
how can i fill automatically this columns using c#.
Note: the row number to start with is 7.
best regards
dghdfghdfghdfghdgh
|
|
|
|
|
Hi,
Kindly note, the problem is that, following commands works perfect only 5 to 10 times in loop
and after then shows error when cursor goes on
"Bitmap mybitmap = new Bitmap(pictureBox2.Image);" after 5 to 10 times in loop.
Error is : !NullReferenceExeption was unhandled
Object reference not set to an instance of an object
-----------------------------------------------
i am using:
-----------------------------------------------
class gp
{
bitmap gp1
{
GetDC(PlatformUSER32.GetDesktopWindow());
CreateCompatibleDC(hdc);
ShowWindow(hdc, 3);
size_.cx = PlatformUSER32.GetSystemMetrics(SM_CXSCREEN);
size_.cy = PlatformUSER32.GetSystemMetrics(SM_CYSCREEN);
CreateCompatibleBitmap(hdc, size_.cx, size_.cy);
}
}
----------------------------------------------
picturebox1.image = gp.gp1()
Bitmap mybitmap = new Bitmap(pictureBox1.Image); <<-- this works perfect 5 to 10 time in loop
after 5 to 10 times it is showing said error.
Kindly help me to solve this problem.
Thank you
(Riaz)
|
|
|
|
|
Windows has a very small pool of device contexts available for programs to do drawing. You're exhausting the pool by not returning the objects once you've finished with them. Call DeleteDC to clean up the compatible DC you created (which you're currently not capturing - this is the return value of CreateCompatibleDC), and ReleaseDC to release the handle you get back from GetDC. Do not mix these calls up - the OS will not like it if you delete one of the pooled DCs.
If you're going to be do any unmanaged drawing I recommend you read 'Programming Windows, Fifth Edition' by Charles Petzold.
DoEvents: Generating unexpected recursion since 1991
|
|
|
|
|
Hi,
1.
from MSDN on GetDC:
a) "After painting with a common DC, the ReleaseDC function must be called to release the DC.
Class and private DCs do not have to be released. ReleaseDC must be called from the same
thread that called GetDC. The number of DCs is limited only by available memory."
b) If the function succeeds, the return value is a handle to the DC for the specified window's client area.
You don;t use the return value???
2.
from MSDN on CreateCompatibleDC:
a) "When you no longer need the memory DC, call the DeleteDC function."
b) If the function succeeds, the return value is the handle to a memory DC.
You don't use the return value???
3.
please show actual code; what you have shown would not compile.
4.
Please use PRE tags to show multi-line code snippets.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
ok Sir,
I am replying with compelete code
|
|
|
|
|
|
OK,
that is looking much better already. it's a pitty you still are not using PRE tags though.
Some remarks:
1.
your while loop has no built-in delay, so it will run as hard as it can. Is that what you
intend? I would suggest you insert a Thread.Sleep(100); or so to slow it down
a bit, leaving some CPU cycles to other tasks.
2.
your while loop continuously replaces the image inside the PictureBox. You don't dispose
of the previous image. Doing so would improve system behavior.
3.
CreateCompatibleBitmap() may return zero; you are aware of that, since you test for it.
But when it does, so does your GetDesktopImage() method, resulting in the NullReference
that you are experiencing.
4.
CreateCompatibleBitmap() returns zero when something fails; MSDN tells you to call
GetLastError() to find out what went wrong, so that's what you should do.
BTW: Don't use P/Invoke to call the native GetLastError(), instead add SetLastError=true
to your DllImport line, and call Marshal.GetLastWin32Error() straight from C#.
If any of this is unclear, look it up in the documentation; make Google your friend.
5.
You may want to repeat remark 4 for other Win32 methods as well.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Thank you very much for your kind consideration
now I will try your said suggestions.
|
|
|
|
|
Hi,
i have populated the menu in a Panel from database . I want to know how do i catch the clicks on the menuitems
Below is the code for generating and populating menu items in a Panel. Please help!
private void PopulateMenu()<br />
{<br />
DataSet ds = GetDataSetForMenu();<br />
Menu menu = new Menu();<br />
<br />
foreach (DataRow parentItem in ds.Tables["Categories"].Rows)<br />
{<br />
MenuItem categoryItem = new MenuItem((string)parentItem["CategoryName"]);<br />
menu.Items.Add(categoryItem);<br />
<br />
foreach (DataRow childItem in parentItem.GetChildRows("Children"))<br />
{<br />
MenuItem childrenItem = new MenuItem((string)childItem["ProductName"]);<br />
categoryItem.ChildItems.Add(childrenItem);<br />
}<br />
}<br />
<br />
Panel1.Controls.Add(menu);<br />
Panel1.DataBind();<br />
}<br />
<br />
private DataSet GetDataSetForMenu()<br />
{<br />
SqlConnection myConnection = new SqlConnection(GetConnectionString());<br />
SqlDataAdapter adCat = new SqlDataAdapter("SELECT * FROM Categories", myConnection);<br />
SqlDataAdapter adProd = new SqlDataAdapter("SELECT * FROM Products", myConnection);<br />
<br />
DataSet ds = new DataSet();<br />
adCat.Fill(ds, "Categories");<br />
adProd.Fill(ds, "Products");<br />
ds.Relations.Add("Children", <br />
ds.Tables["Categories"].Columns["CategoryID"], <br />
ds.Tables["Products"].Columns["CategoryID"]);<br />
return ds;<br />
}
Thanks in advance for your help!
adi_nik
|
|
|
|
|
|
Thanks for your suggestion.. it helped!
adi_nik
|
|
|
|
|
I've never heard of a the Menu class.
I've heard of MainMenu, MenuStrip, ContextMenu, ToolStrip, but not that. Anyway, if its anything like the previous three components, you can capture the click events on the items themselves like someone already mentioned. Or you can handle the MenuItemsClicked event of the menu. Heres an example from a toolstrip:
<br />
ToolbarControl.ItemClicked += new ToolStripItemClickedEventHandler(ToolbarControl_ItemClicked);<br />
<br />
private void ToolbarControl_ItemClicked(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)<br />
{<br />
switch (e.ClickedItem.Name)<br />
{<br />
case "Item1":<br />
DoWork();<br />
break;<br />
case "AnotherItem":<br />
DoSomethingElse();<br />
break;<br />
}<br />
<br />
}<br />
Lester
http://www.lestersconyers.com
|
|
|
|
|
hello evreybody,
i am creating win application in C#. this is my problem-> i am seahing in google. I visited some links.
i hve one button and one textbox in my form. . If i click the button all the visited Url text should come to the button.
can anyone help me ? it very urgent.
thanks in advance.
Senthil.P
|
|
|
|
|
HI,
Is it possible to create a floating/dockable form in C# winforms.
Something similar to Properties/Solution Explorer window in Visual
Studio.net.
Thanks.
|
|
|
|
|
|
Hi All,
I have a project which includes multiple long windows forms. Some of these forms have around 200
fields. These forms will use a combination of custom user controls and third
party components. If it is at all possible I would like to avoid manually
adding a thousand fields to Print Documents. What would be a best practice for
sending such large windows forms to a printer? Is anyone aware of any third
party components that would provide a solution for this problem? Could this
problem be solved by looping through the controls on the form somehow? Any
advice or direction that you could give me would be greatly appreciated.
Thanks in Advance,
Mani.
modified on Tuesday, April 8, 2008 2:11 AM
|
|
|
|
|
Hi,
I would like to dynamically add TabPages to my form depending on a number of Sheets$ that are contained in a spredsheet I'm loading to a datagrid. At the moment I have an application that loads a spreadsheet to a datagrid, but it only loads one (the default) worksheet. How can I dynamically create tabpages depending on the number of worksheets in the spreasheet and load them to the datagrid. Below is the code of what the application can do so far:
//This takes the Excel file from a specific location
//and displays it in the datagrid
private void btnOpenFile_Click(object sender, EventArgs e)
{
// prepare open file dialog to only search for excel files
this.ofd.FileName = "*.xls";
if (this.ofd.ShowDialog() == DialogResult.OK)
{
try
{
// Here is the call to Open a Workbook in Excel
// It uses most of the default values (except for the read-only which we set to true)
Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(ofd.FileName, 0, true, 5,
"", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, true, true);
// get the collection of sheets in the workbook
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
// get the first and only worksheet from the collection of worksheets
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
//get start and end rows
Object[] startRow = { worksheet.get_Range("A4", "O4") };
int endRow = worksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing).Row;
//Check if all columns are according to spec
if ((worksheet.get_Range("A3", "A3").Text.ToString() == "Template") &&
(worksheet.get_Range("B3", "B3").Text.ToString() == "Error Code") &&
(worksheet.get_Range("C3", "C3").Text.ToString() == "Error Name") &&
(worksheet.get_Range("D3", "D3").Text.ToString() == "Error Description") &&
(worksheet.get_Range("E3", "E3").Text.ToString() == "Error Cause") &&
(worksheet.get_Range("F3", "F3").Text.ToString() == "Source") &&
(worksheet.get_Range("G3", "G3").Text.ToString() == "Destination") &&
(worksheet.get_Range("H3", "H3").Text.ToString() == "Category") &&
(worksheet.get_Range("I3", "I3").Text.ToString() == "Severity") &&
(worksheet.get_Range("J3", "J3").Text.ToString() == "Threshold") &&
(worksheet.get_Range("K3", "K3").Text.ToString() == "Responsible for Resolution") &&
(worksheet.get_Range("L3", "L3").Text.ToString() == "Action") &&
(worksheet.get_Range("M3", "M3").Text.ToString() == "ECS Resubmit Y/N") &&
(worksheet.get_Range("N3", "N3").Text.ToString() == "ECS Auto Resubmit Y/N") &&
(worksheet.get_Range("O3", "O3").Text.ToString() == "ECS XML Editing Y/N") &&
(worksheet.get_Range("P4", "P4").Text.ToString() == "ECS Client Notification Y/N – If Yes, supply info") &&
(worksheet.get_Range("Q4", "Q4").Text.ToString() == "Notification Type Email SMS or Both") &&
(worksheet.get_Range("R4", "R4").Text.ToString() == "E-Mail Group") &&
(worksheet.get_Range("S4", "S4").Text.ToString() == "SMS Number") &&
(worksheet.get_Range("T4", "T4").Text.ToString() == "Escalation Y/N") &&
(worksheet.get_Range("U4", "U4").Text.ToString() == "Escalate to who?"))
{
//MessageBox.Show("The headings in the spreadsheet are correct! \nYou may proceed.","Headings", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("The Headings should be: \nTemplate, Error Code, Error Name," +
" Error Description, Error Cause, Source, Destination, Category, Severity, Threshold, Responsible for Resolution, Action,ECS Resubmit Y/N, " +
" ECS Auto Resubmit Y/N, ECS XML Editing Y/N, ECS Client Notification Y/N – If Yes, supply info, " +
" Notification Type Email SMS or Both, E-Mail Group, SMS Number, Escalation Y/N, Escalate to who?, " +
". \n\nPlease load the correct file or Click the 'Create Blank Template' button to get a blank Template.", "Error : Headings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Check if all the required tables are there
if ((worksheet.get_Range("H3", "H3").Text.ToString() == "Category") &&
(worksheet.get_Range("I3", "I3").Text.ToString() == "Severity"))
{
//MessageBox.Show("All the required tables were found \nYou may proceed.", "Required Tables", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("The following tables are required: \nCategory, Severity\n\nPlease ensure that these tables exist.",
"Error : Required Tables", MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Windows.Forms.Application.Exit();
ExcelObj.Visible = false;
}
// loop through the rows of the spreadsheet and place each row in the datagrid
for (int i = 5; i <= endRow; i++)
{
Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range("A" + i.ToString(), "Z" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value2;
string[] strArray = ConvertToStringArray(myvalues);
//Add the rows from the spreadsheet to the datagrid
DataGridViewRow row = new DataGridViewRow();
Object[] vals = strArray;
row.CreateCells(dgOutput, vals);
dgOutput.Rows.Add(row);
}
}
catch (Exception EX)
{
MessageBox.Show("Error: " + EX.Message, "Error opening Excel..");
}
}
}
string[] ConvertToStringArray(System.Array values)
{
// create a new string array
string[] theArray = new string[values.Length];
theArray[0] = "";
// loop through the 2-D System.Array and populate the 1-D String Array
for (int i = 1; i < values.Length; i++)
{
if (values.GetValue(1, i) == null)
theArray[i] = "";
else
theArray[i] = (string)values.GetValue(1, i).ToString();
}
return theArray;
}
Please help.
Mvelo Walaza
Developer
Telkom SA
|
|
|
|
|
I'm not terribly familiar with the Microsoft.Office namespace but after you get the collection of WorkSheets called sheets, I would think you can loop through them all and create pages. Something like this:
<br />
<br />
TabPage page;<br />
DataGridView dgv;<br />
foreach(Worksheet sheet in sheets)<br />
{<br />
page = new TabPage();<br />
dgv = new DataGridView();<br />
<br />
--enter code here--<br />
<br />
page.Controls.Add(dgv);<br />
<br />
this.tabControl1.TabPages.Insert(0, page);<br />
}<br />
Hope this helps.
Lester
http://www.lestersconyers.com
modified on Monday, April 7, 2008 10:25 AM
modified on Monday, April 7, 2008 11:07 AM
|
|
|
|
|
Could you remove the < - - i think it is causing the page not rendering after your post on FireFox.
|
|
|
|
|
Hi,
Thanks for the reply. Should I have put this code in the constructor or should I put it under the button that loads the spreadsheet? Should I put the tabControl from the ToolBox or should I only use the dynamically created one? I have put in your suggested code but when I load the spreadsheet my form just becomes blank and the tabs do not get created.
Mvelo Walaza
Developer
Telkom SA
|
|
|
|
|
I would put this code under the button that loads the spreadsheet. If not, you'll get a problem. And I need to modify the code I submitted. In the code I had you create a new TabControl without adding it to the form. Hopefully, you already have a tab control on the page so the designer can set a bunch of properties. I'm going to modify my original code based on that assumption.
If not, you'll have to do something like
<br />
this.Controls.Add(tabControl1);<br />
Lester
http://www.lestersconyers.com
|
|
|
|
|
Thank you so much, I am making so much progress in one day! The problem is, it only shows the data of only one worksheet. It shows the tabs and their worksheets names but does not add the datagrid and the data to the tabpage. What could I be doing wrong, here's the code:
//This takes the Excel file from a specific location
//and displays it in the datagrid
private void btnOpenFile_Click(object sender, EventArgs e)
{
// prepare open file dialog to only search for excel files
this.ofd.FileName = "*.xls";
if (this.ofd.ShowDialog() == DialogResult.OK)
{
try
{
// Here is the call to Open a Workbook in Excel
// It uses most of the default values (except for the read-only which we set to true)
Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(ofd.FileName, 0, true, 5,
"", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, true, true);
// get the collection of sheets in the workbook
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
//theWorkbook.Worksheets[sheets];
// get the first and only worksheet from the collection of worksheets
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
TabControl tbControl = new TabControl();
this.Controls.Add(tbControl);
tbControl.Dock = DockStyle.Bottom;
tbControl.Height = 660;
TabPage page;
//DataGridView dgv;
foreach (Worksheet sheet in sheets)
{
page = new TabPage(sheet.Name.ToString());
//dgOutput = new DataGridView();
//get start and end rows
Object[] startRow = { worksheet.get_Range("A4", "O4") };
int endRow = worksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing).Row;
//Check the columns...Removed
// loop through the rows of the spreadsheet and place each row in the datagrid
for (int i = 5; i <= endRow; i++)
{
Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range("A" + i.ToString(), "Z" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value2;
string[] strArray = ConvertToStringArray(myvalues);
//Add the rows from the spreadsheet to the datagrid
DataGridViewRow row = new DataGridViewRow();
Object[] vals = strArray;
row.CreateCells(dgOutput, vals);
dgOutput.Rows.Add(row);
}
page.Controls.Add(dgOutput);
tbControl.TabPages.Insert(0, page);
}
}
catch (Exception EX)
{
MessageBox.Show("Error: " + EX.Message, "Error opening Excel..");
}
}
Mvelo Walaza
Developer
Telkom SA
|
|
|
|
|