Jump to content
Xtreme .Net Talk

joe_pool_is

Avatar/Signature
  • Posts

    512
  • Joined

  • Last visited

Everything posted by joe_pool_is

  1. It *should* be sending immediately. What does your code look like? How do you know it is taking "about one second"?
  2. Here is the Console version, which does not throw an exception (though I can't see the output) class Program { Button button1; ListView listView1; static void Main(string[] args) { Program pgm = new Program(); pgm.Go(); } public void Go() { button1 = new Button(); button1.Enabled = true; listView1 = new ListView(); listView1.Width = 500; listView1.Clear(); listView1.Columns.Add("TestName", 140); listView1.Columns.Add("Result", (listView1.Width - listView1.Columns[0].Width - 2)); string serialNumber = "123456789A"; ThreadParameter tp = new ThreadParameter(serialNumber); tp.ProgressChanged += new ThreadParameter.ReportProgressDelegate(Thread_Report); Thread th = new Thread(new ParameterizedThreadStart(Thread_Routine)); th.IsBackground = true; th.Start(tp); while (!th.IsAlive) Thread.Sleep(0); button1.Enabled = false; th.Join(); button1.Enabled = true; } void Thread_Report(int step, object data) { if ((data != null) && (data is DataTable)) { DataTable table = (DataTable)data; const string TEST_RESULT = "Test_Result"; switch (step) { case 0: listView1.Items.Add(new ListViewItem(new string[] { "Row 1", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 2", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 3", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 4", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 5", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 6", string.Empty })); break; case 1: if ((2 < table.Rows.Count) && (table.Columns.Contains(TEST_RESULT))) { listView1.Items[0].SubItems[1].Text = table.Rows[1][TEST_RESULT].ToString(); listView1.Items[1].SubItems[1].Text = table.Rows[2][TEST_RESULT].ToString(); } break; case 2: if ((4 < table.Rows.Count) && (table.Columns.Contains(TEST_RESULT))) { listView1.Items[2].SubItems[1].Text = table.Rows[3][TEST_RESULT].ToString(); listView1.Items[3].SubItems[1].Text = table.Rows[4][TEST_RESULT].ToString(); } break; case 3: if ((6 < table.Rows.Count) && (table.Columns.Contains(TEST_RESULT))) { listView1.Items[4].SubItems[1].Text = table.Rows[5][TEST_RESULT].ToString(); listView1.Items[5].SubItems[1].Text = table.Rows[6][TEST_RESULT].ToString(); } break; default: break; } } } void Thread_Routine(object threadParam) { ThreadParameter tp = (ThreadParameter)threadParam; const string sqlConn = "SUPPLY_YOUR_CONNECTION_STRING"; using (SqlConnection conn = new SqlConnection(sqlConn)) { int step = 0; string sqlText = "sp_GetPartRecord"; DataSet ds = new DataSet(); using (DataTable table = new DataTable()) { tp.ReportProgress(step++, table); } using (SqlDataAdapter da = new SqlDataAdapter(sqlText, sqlConn)) { DataTable table = new DataTable(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@SN", tp.SerialNumber); Console.WriteLine("Step {0}", step); da.Fill(table); ds.Tables.Add(table); tp.ReportProgress(step++, ds.Tables[ds.Tables.Count - 1]); } using (SqlDataAdapter da = new SqlDataAdapter(sqlText, sqlConn)) { DataTable table = new DataTable(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@SN", tp.SerialNumber); Console.WriteLine("Step {0}", step); da.Fill(table); ds.Tables.Add(table); tp.ReportProgress(step++, ds.Tables[ds.Tables.Count - 1]); } using (SqlDataAdapter da = new SqlDataAdapter(sqlText, sqlConn)) { DataTable table = new DataTable(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@SN", tp.SerialNumber); Console.WriteLine("Step {0}", step); da.Fill(table); ds.Tables.Add(table); tp.ReportProgress(step++, ds.Tables[ds.Tables.Count - 1]); } } } }
  3. I have a test application that sends data from a new thread back to the main thread. I would prefer to use the BackgroundWorker class (which is perfect for doing this), but I can not, as explained in my earlier thread No BackgroundWorker Allowed. I designed the custom class ThreadParameter (below) with a delegate and a corresponding an event. The event, in turn, is intended to Invoke the method in the main thread; however, whenever the method in the main thread is called and I attempt to access one of the controls on my form, I get an InvaidOperationException telling me that I can not access the control from a thread other than where it is owned. I thought I was! So, I wrote an even more basic application that was Console based because I wanted to cut out all of the fat before posting it here. Ugh! The Console Application runs without a hitch, and it is mostly from cut and paste from my Windows Application! Below are the "meat and potatoes" of my two basic applications. Could someone with vast knowledge (i.e. Marble Eater or Plausibly) kindly help me see the error to my ways? Both versions (Windows and Console) take an instance of this custom class that I created as the thread's Start parameter: public class ThreadParameter { string _serialNumber; public delegate void ReportProgressDelegate(int step, DataTable data); public event ReportProgressDelegate ProgressChanged; public ThreadParameter(string serialNumber) { _serialNumber = serialNumber; ProgressChanged = null; } public void ReportProgress(int step, DataTable data) { if (ProgressChanged != null) { ProgressChanged.Invoke(step, data); } } public string SerialNumber { get { return _serialNumber; } } } Here is the Windows version, which throws the InvalidOperationException: public partial class Form1 : Form { public Form1() { InitializeComponent(); } void button1_Click(object sender, EventArgs e) { Go(); } void Go() { listView1.Clear(); listView1.Columns.Add("TestName", 140); listView1.Columns.Add("Result", (listView1.Width - listView1.Columns[0].Width - 2)); string serialNumber = "123456789A"; ThreadParameter tp = new ThreadParameter(serialNumber); tp.ProgressChanged += new ThreadParameter.ReportProgressDelegate(Thread_Report); Thread th = new Thread(new ParameterizedThreadStart(Thread_Routine)); th.IsBackground = true; th.Start(tp); while (!th.IsAlive) Thread.Sleep(0); button1.Enabled = false; th.Join(); button1.Enabled = true; } void Thread_Report(int step, object data) { if ((data != null) && (data is DataTable)) { DataTable table = (DataTable)data; const string TEST_RESULT = "Test_Result"; switch (step) { case 0: listView1.Items.Add(new ListViewItem(new string[] { "Row 1", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 2", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 3", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 4", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 5", string.Empty })); listView1.Items.Add(new ListViewItem(new string[] { "Row 6", string.Empty })); break; case 1: if ((2 < table.Rows.Count) && (table.Columns.Contains(TEST_RESULT))) { listView1.Items[0].SubItems[1].Text = table.Rows[1][TEST_RESULT].ToString(); listView1.Items[1].SubItems[1].Text = table.Rows[2][TEST_RESULT].ToString(); } break; case 2: if ((4 < table.Rows.Count) && (table.Columns.Contains(TEST_RESULT))) { listView1.Items[2].SubItems[1].Text = table.Rows[3][TEST_RESULT].ToString(); listView1.Items[3].SubItems[1].Text = table.Rows[4][TEST_RESULT].ToString(); } break; case 3: if ((6 < table.Rows.Count) && (table.Columns.Contains(TEST_RESULT))) { listView1.Items[4].SubItems[1].Text = table.Rows[5][TEST_RESULT].ToString(); listView1.Items[5].SubItems[1].Text = table.Rows[6][TEST_RESULT].ToString(); } break; default: break; } } } void Thread_Routine(object threadParam) { ThreadParameter tp = (ThreadParameter)threadParam; const string sqlConn = "SUPPLY_YOUR_CONNECTION_STRING"; using (SqlConnection conn = new SqlConnection(sqlConn)) { int step = 0; string sqlText = "sp_GetPartRecord"; DataSet ds = new DataSet(); using (DataTable table = new DataTable()) { tp.ReportProgress(step++, table); } using (SqlDataAdapter da = new SqlDataAdapter(sqlText, sqlConn)) { DataTable table = new DataTable(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@SN", tp.SerialNumber); da.Fill(table); ds.Tables.Add(table); tp.ReportProgress(step++, ds.Tables[ds.Tables.Count - 1]); } using (SqlDataAdapter da = new SqlDataAdapter(sqlText, sqlConn)) { DataTable table = new DataTable(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@SN", tp.SerialNumber); da.Fill(table); ds.Tables.Add(table); tp.ReportProgress(step++, ds.Tables[ds.Tables.Count - 1]); } using (SqlDataAdapter da = new SqlDataAdapter(sqlText, sqlConn)) { DataTable table = new DataTable(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@SN", tp.SerialNumber); da.Fill(table); ds.Tables.Add(table); tp.ReportProgress(step++, ds.Tables[ds.Tables.Count - 1]); } } } } Getting this to work would be a considerable milestone for me. If (after getting the code itself to work) someone sees bad logic or bad techniques, I would very much like to hear your input. Years ago, my major was physics, so I don't always take the best approach to software development. Regards, Joe
  4. I've got a really nice routine I wrote with a BackgroundWorker, it works beautifully, and reduces the time of looking up my parts in our database from 4 seconds to under 1 second. At the heart of my BackgroundWorker is the DoWork delegate. It looks up information from 5 different tables in our database, but instead of processing that data, the data is transferred to the ProgressChanged delegate so the DoWork delegate can go on to query the next table. When the entire process is finished, the RunWorkerCompleted delegate displays the result of all the information to my form. I want to use this time saving technique on my Windows Mobile applications. I know this message board does not have a Windows Mobile section, so I'll tell you my problem: The Windows Mobile "reduced feature" set does not include the BackgroundWorker class, but rather it includes the System.Threading namespace only. Now, I am struggling to find out how I can achieve the same techniques using the System.Threading namespace only. I want to find a way to duplicate things I do in my BackgroundWorker class in the System.Threading namespace. Here are the key elements I want to keep from my BackgroundWorker delegates: DoWork: My main issue here is finding out how to implement the ReportProgress method, as detailed below: void Worker_GetData(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; MyParameter obj = (MyParameter)e.Argument; string partNumber = obj.PartNumber; string sqlText; using (SqlConnection con = new SqlConnection(obj.ConnString)) { sqlText = "SELECT * FROM Table1 WHERE (PartNumber=@PartNumber)"; using (SqlDataAdapter da = new SqlDataAdapter(sqlText, con)) { DataTable table = new DataTable(); da.SelectCommand.Parameters.Add("@PartNumber", SqlDbType.Char, 10).Value = partNumber; da.Fill(table); worker.ReportProgress(1, table); } sqlText = "SELECT * FROM Table2 WHERE (PartNumber=@PartNumber)"; using (SqlDataAdapter da = new SqlDataAdapter(sqlText, con)) { DataTable table = new DataTable(); da.SelectCommand.Parameters.Add("@PartNumber", SqlDbType.Char, 10).Value = partNumber; da.Fill(table); worker.ReportProgress(2, table); } // etc. for all 5 tables } } The ProgressChanged delegate also does a lot of work for me: void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { lock (_objProgress) { DataTable table = (DataTable)e.UserState; switch (e.ProgressPercentage) { case 1: // process Table1 information break; case 2: // process Table2 information break; // etc. for all 5 tables } } } If I use System.Threading, how would I: Report the thread's progress back to the main thread Catch messages from my thread Know when my thread has completed I have found numerous examples on the web on how to use the System.Threading namespace, but no one gets into how to pass class objects from the thread back like I am able to do in the BackgroundWorker class. The closest I have found is to invoke a textbox or other basic control. Thanks in advance for your input, Joe
  5. Personally, I use this site for reference quite often, so I wanted to update this with some SQL CE links: Walkthrough: Using SQL Server Compact Edition in an Application: http://msdn.microsoft.com/en-us/library/aa983340(VS.80,printer).aspx How to: Add a SQL Server Compact Edition Database to a Project http://msdn.microsoft.com/en-us/library/aa983322(VS.80,printer).aspx How to: Deploy a SQL Server Compact Edition Database with an Application: http://msdn.microsoft.com/en-us/library/aa983326(VS.80,printer).aspx (The links could be dead at any moment, knowing Microsoft, hence why I included the titles.) Other helpful files to search by on Microsoft's Download Center: Microsoft SQL Server 2005 Compact Edition: File Name: SQLServerCE31-EN.msi Version: 1 KB Article: KB920700 Size: 1.7 MB Microsoft SQL Server 2005 Compact Edition Developer Software Development Kit File Name: SSEC31SDK-ENU.msi Version: 1 KB Article: KB920700 Size: 35.5 MB Microsoft SQL Server 2005 Compact Edition Tools for Visual Studio 2005 Service Pack 1 File Name: SSCE31VSTools-ENU.exe KB Article: N/A Size: 27.6 MB I hope some of you get some good use out of my research! ~Joe
  6. The main thing you'll find is that Windows Mobile works on a reduced set of tools; however, all of the necessary requirements can generally still be met. My VB is rusty, so the syntax may not be correct, but take this example: This line will not compile under Windows Mobile: Dim text as String = "123@domain.com" If (text.Contains("@domain.com") = True) Then ' do stuff End If Why won't this compile under Windows Mobile? Answer: It does not have the bloated method "Contains". So, how would you check your text, you ask? The answer is to use a more fundamental check like this: Dim text as String = "123@domain.com" If (-1 < text.IndexOf("@domain.com") = True) Then ' do stuff End If Obviously, these are smaller, more efficient calls, or they would not be the features chosen for the compact Mobile edition, which have limited space and much slower processors. On the plus side, once you get accustomed to coding for Mobile applications, you'll find yourself using the smaller/faster calls in all of your code - even for Windows applications!
  7. I'm going out of town this weekend to look at doing a job for a client. It looks like they are wanting a way to exchange information between their 5 team members in remote locations using an Access database, whereas I generally spend most of my time working with MS SQL 2000. What key differences would I need to know about Access before going out there? Since I don't work with it, I don't know what to look out for. I know SQL CE is supposed to be able to replace Access, and I'd like to talk them into this. However, I've never tried building an installer for SQL CE in one of my application's setup files, and I'd rather not have a SQL CE database if it is going to require a DBA to tag along behind it. I'm using C# in VS2005, but I can read VB.NET. Any thoughts or recommendations? Regards, ~Joe
  8. Thanks Jumpy. The only reason I didn't take your suggestion is because MS could mess up the Lucida font the next time. Anyway, here's the approach I took: I set the font in my designer to be the default Microsoft San Seriff, then used this code in the Form's Load Event Handler: try { Font courier = new Font(FontFamily.GenericMonospace, 10.0F); txtOutput.Font = courier; } catch { // if it fails, the standard font will display }
  9. My application has been using Courier New for a long time, but lately it seems like this font keeps throwing errors whenever someone tries to load the font. I get something like, "System.Font.Courier New does not support style Regular". After digging, I find that this is on a form that is set up to show tabular data using a fixed width font. Courier New has worked on these systems in the past, but I don't know. Maybe a Microsoft Update modified them or something. Anyway, Courier New often causes my applications to crash. Is there another generic, fixed width font that I can use besides this? The only thing I want is for my font to be fixed width and set to size 10, 12, or 14. Thanks in advance, Joe --- Append: I'm googling this text: "Font 'Courier New' does not support style 'Regular'" There are a *lot* of reports about this as of late. Has Microsoft released a patch that corrupted this file?
  10. I don't know a solution, but I would be very interested in knowing how you have created what you have to date. I'd like to put something like that into our BETA releases under the Suggestions and Bugs report tool.
  11. Could a new area be created for Mobile Development? (Pocket PCs, Windows Mobile 6, Windows CE) I get tired of having to rely on Microsoft's MSDN forum, which often responds with something about their network being busy.
  12. That got me started. Thanks! Along the way, I found this technique that looks really clean: public class FormValues { int otherValue; string[,] matrix; public string this[int X, int Y] { get { return matrix[X, Y]; } set { matrix[X, Y] = value; } } public FormValues() { otherValue = 0; matrix = new int[8, 8] { // blah blah blah! } public int Other { get { return otherValue; } } }
  13. I've got a 8x8 array. Each element of the array will contain an object that consists of a letter, a color, and a double value. Creating and working with arrays in my class is not the hard part. The hard part is how do I make them publicly accessible outside of my class? In other words, how would I write the Get and Set properties for it? I'm guessing I should not be using the standard 8x8 array, and instead I should be using ...what? And, how would I implement it? I'm looking to stay within Microsoft's Best Practices, if I can. As always, help, links or advice is always appreciated!
  14. I have a lot of data already displayed in a DataGridView object. To sort it, add custom rows, etc., my plan is to take all of that data and copy it over to a DataTable object, manipulate it, then just copy it back over to the DataGridView object // dataGridView1.DataSource = dataTable1.DefaultView; However, I can't seem to find a way to get the data from the DataGridView object over to the DataTable object. Everything I try says the DataTable method is Read Only. Does anyone know how to do this? Regards, Joe
  15. While I have your ear, I've got a related question: There are times that I write a block of code in a try/catch routine, and when I run the application, I still get thrown out at the program's entry point with an unhandled exception. What causes those? How do I prevent those?
  16. The more I learn about exceptions, the more I feel like I should *not* be catching and dismissing general exceptions in my code like I do: try { DoThis1(); } catch (Exception err) { LogError(err); } So, what I've been trying to do is catch the exceptions that could be thrown by particular routines, but I don't know which ones need to be caught and which ones are obvious checks that don't need catching. Take the ArgumentNullException. If I do a simple check on my object, if (obj != null) { DoThis2(); }can I eliminate the ArgumentNullException? For sending a simple email, I find myself catching about 5 exceptions: try { SmtpClient client = new SmtpClient(strIpAddress); client.Send(email); } catch (SmtpFailedRecipientsException) { // handle it } catch (ArgumentNullException) { // handle it } catch (SmtpException) { // handle it } catch (InvalidOperationException) { // handle it } catch (ArgumentOutOfRangeException) { // handle it } catch (ObjectDisposedException) { // handle it }Is this ridiculous or is it just me? So I go to build my application, and VS2005 throws up and error: Where is the documentation on what order to catch my exceptions in? I found documentation on Exceptions on MSDN, but nothing telling me what order they can be called in. Sometimes I just want to go back to catching the general exceptions, but I also want good code.
  17. Finally: Background Completevoid Worker_FillDataGridComplete(object sender, RunWorkerCompletedEventArgs e) { _parent.AuthenticationReset(); Cursor = Cursors.Default; _frmProgress.Close(); if (e.Error == null) { if ((e.Result is ZTreeParam) && (e.Result != null)) { ZTreeParam tp = (ZTreeParam)e.Result; DataTable table = new DataTable(tp.DataSet1.DataSetName); foreach (DataTable dsTable in tp.DataSet1.Tables) { try { table.Merge(dsTable); } catch (Exception err) { Global.LogError("Reporter - Worker_FillDataGridComplete", err); } } DataGridView_Clear(); DataGridView1.DataSource = table.DefaultView; if (DataGridView1.CurrentRow != null) { DataGridView1.CurrentRow.Selected = false; } UpdateStatusBar(string.Format("{0} records found", DataGridView1.Rows.Count)); if (tp.ColumnName.IndexOf("System_ID") == -1) { if ((0 < DataGridView1.Rows.Count) && (((tp.ColumnName == _EMPLOYEE) || (tp.ColumnName == "Operator")) || ((tp.ColumnName == _SERIALNUM) || (tp.ColumnName == "Coils")) || (_clearTree == true))) { List<string> StringList = new List<string>(DataGridView1.Rows.Count); for (int i = 0; i < DataGridView1.Rows.Count; i++) { DataGridViewRow row = DataGridView1.Rows[i]; string value = string.Empty; if ((tp.ColumnName == _EMPLOYEE) || (tp.ColumnName == "Operator")) { value = row.Cells[tp.Column].Value.ToString().Trim(); if (Action == MainAction.Reports) { if (-1 < value.IndexOf("Summary")) { foreach (DataGridViewCell cell in row.Cells) { cell.Style.BackColor = Color.Yellow; cell.Style.SelectionBackColor = Color.Gold; } } if (_ReportOpt[_nFilter1Key] == _LEAKSITES) { // nothing to do, I don't think. } else if (_ReportOpt[_nFilter1Key] == _INSPECTIONS) { value = string.Empty; } } } else if ((tp.ColumnName == _SERIALNUM) || (tp.ColumnName == "Coils")) { value = row.Cells[tp.Column].Value.ToString().Trim(); if ((Action == MainAction.Reports) && (_ReportOpt[_nFilter1Key] == _WORKORDER)) { if (0 < value.IndexOf("Total")) { foreach (DataGridViewCell cell in row.Cells) { cell.Style.BackColor = Color.Yellow; cell.Style.SelectionBackColor = Color.Gold; } } else { if (AcpCoil.CheckFormat(value) == string.Empty) { Color bgColor = (i % 2 == 0) ? Color.PaleGreen : Color.Lime; for (int j = 4; (j < 11) && (j < row.Cells.Count); j++) { string txt = row.Cells[j].Value.ToString(); if ((Global.IsNumeric(txt) == true) && (0 < Global.ToInt32(txt))) { row.Cells[j].Style.BackColor = bgColor; row.Cells[j].Style.SelectionBackColor = Color.Silver; } } } else { value = string.Empty; } } } } else { Console.WriteLine(tp.ColumnName); } if (((value != string.Empty) && (StringList.Contains(value) == false)) || //((Action == MainAction.Reports) && (m_ReportOpt[m_nFilter1Key] == m_LEAKSITES)) || (value == "Leak Site Summary") ) { StringList.Add(value); } } if ((0 < StringList.Count) && (_clearTree == true)) { BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.ProgressChanged += new ProgressChangedEventHandler(Worker_ProgressChanged); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_FillTreeComplete); if ((Action == MainAction.Reports) && (_ReportOpt[_nFilter1Key] == _LEAKSITES)) { List<DataRow> Rows = new List<DataRow>(StringList.Count); foreach (string emp in StringList) { bool ok = true; string[] split1 = emp.Split(new char[] { '(' }); string[] split2 = split1[0].Substring(0, split1[0].Length).Trim().Split(_blankspace); string sql = string.Empty; if (split2.Length == 2) { sql = string.Format("(FIRSTNAME Like '{0}%') AND (LASTNAME Like '%{1}')", split2[0], split2[1]); } else if (split2.Length == 3) { sql = string.Format("((FIRSTNAME Like '{0}%') OR (FIRSTNAME Like '{1}%')) " + "AND ((LASTNAME Like '%{1}') OR (LASTNAME Like '%{2}'))", split2[0], split2[1], split2[2]); } else { ok = false; } if (ok == true) { DataRow[] dr = Global.CpAppDataSet.Tables[_EMPLOYEEINFO].Select(sql); DataRow tmp = null; for (int i = 0; i < dr.Length; i++) { if (tmp == null) { tmp = dr[i]; } else { if ((int)tmp["COUNT"] < (int)dr[i]["COUNT"]) { tmp = dr[i]; } } } if (tmp != null) Rows.Add(tmp); } } if (0 < Rows.Count) { worker.DoWork += new DoWorkEventHandler(Worker_FillTreeWithEmployees); worker.RunWorkerAsync(Rows.ToArray()); } } else { worker.DoWork += new DoWorkEventHandler(Worker_FillTreeWithCoils); worker.RunWorkerAsync(StringList.ToArray()); } if (worker.IsBusy == true) { Cursor = Cursors.WaitCursor; } } else { _clearTree = true; // subsequent searches will want to clear this tree information } } else { MessageBox.Show("No records found.", "Search Complete", MessageBoxButtons.OK, MessageBoxIcon.Information, 0); } } if (_cols2hide != null) { foreach (string col in _cols2hide) { if (DataGridView1.Columns.Contains(col) == true) { DataGridView1.Columns[col].Visible = false; } } } DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); _footer = string.Format("{0} - {1} View\r\nCreated {2}", Title, tp.ColumnName, DateTime.Now); } else if (e.Result is string) { MessageBox.Show(e.Result.ToString()); UpdateStatusBar(string.Format("Collect Data Error: {0}", e.Result.ToString())); } } else if (e.Error != null) { UpdateStatusBar(string.Format("Collect Data Error: {0}", e.Error.Message)); _frmProgress.Close(); } else if (e.Cancelled == true) { UpdateStatusBar("Data Collection was cancelled."); _frmProgress.Close(); } }
  18. Third: Background Progress Changedvoid Worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { _parent.AuthenticationReset(); ZThreadParam obj = null; _frmProgress.ProgressValue = e.ProgressPercentage; if (_frmProgress.ProgressValue == -1) { _frmProgress.ProgressString = string.Empty; _frmProgress.TimeLeftString = string.Empty; } else if (e.UserState != null) { if (e.UserState is ZThreadParam) { obj = (ZThreadParam)e.UserState; if ((_frmProgress == null) || (_frmProgress.Cancelled == true)) { BackgroundWorker worker = sender as BackgroundWorker; worker.CancelAsync(); return; } _frmProgress.HeaderText = obj.ThreadString; UpdateStatusBar(obj.ThreadString); } else if (e.UserState is string) { UpdateStatusBar((string)e.UserState); } if (_frmProgress.TimeLeftString == "Calculating...") { _threadTime = DateTime.Now; _frmProgress.TimeLeftString = "Calculating....."; } else { TimeSpan span = (DateTime.Now - _threadTime); if (0 < span.TotalSeconds) { int count = obj.Count + 1; int num = obj.Total - count; double numPerSec = (double)count / (double)span.TotalSeconds; if (numPerSec == 0) numPerSec = 1; span = new TimeSpan(0, 0, (int)(num / numPerSec)); string statusFile = string.Format("{0} of {1}", count, obj.Total); string statusTime = string.Format("{0}:{1}", span.Minutes.ToString("00"), span.Seconds.ToString("00")); _frmProgress.ProgressString = statusFile; _frmProgress.TimeLeftString = statusTime; } } } else { _frmProgress.HeaderText = "Working..."; } }
  19. Second: Background Workervoid Worker_FillDataGrid(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; worker.ReportProgress(-1); if (e.Argument is ZTreeParam) { ZTreeParam tp = (ZTreeParam)e.Argument; using (SqlDataAdapter da = new SqlDataAdapter()) { if (tp.StoredProcedure.CommandType == CommandType.StoredProcedure) { da.SelectCommand = tp.StoredProcedure; } else if (tp.StoredProcedure.CommandType == CommandType.Text) { da.SelectCommand = tp.StoredProcedure; } else { // I added the "else if" line above. Does the line below ever still get called? da.SelectCommand.CommandText = tp.ThreadString; // disable this break point if so } try { if (Action == MainAction.Reports) { if (_ReportOpt[_nFilter1Key] == _LEAKSITES) { string strSummary = string.Empty; if ((tp.Extra != null) && (tp.Extra != string.Empty)) { strSummary = tp.StoredProcedure.CommandText; da.SelectCommand.CommandText = tp.Extra; using (DataTable table = new DataTable()) { da.Fill(table); tp.DataSet1.Tables.Add(table); } } if (strSummary != string.Empty) { da.SelectCommand.CommandText = strSummary; } } } using (DataTable table = new DataTable()) { da.Fill(table); tp.DataSet1.Tables.Add(table); } } catch (SqlException err) { Global.LogError("Reporter - Worker_FillDataGrid", err); e.Result = err; return; } } e.Result = tp; } else { e.Result = null; } }
  20. Here is a working example (using C#) that might help get the point across. It is too long to post in one message, so it will be as follows: Background Constructor Background Worker Background Progress Changed Background Completed I apologize for not customizing it so that it is generic and easy to understand, but maybe including all my code will give you some pointers on new things to try. First: Background Constructor void Fill_DataGridView(ZTreeParam tp) { using (BackgroundWorker worker = new BackgroundWorker()) { worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += new DoWorkEventHandler(Worker_FillDataGrid); worker.ProgressChanged +=new ProgressChangedEventHandler(Worker_ProgressChanged); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_FillDataGridComplete); worker.RunWorkerAsync(tp); if (worker.IsBusy == true) { Cursor = Cursors.WaitCursor; } } }
  21. Chris, First off, all of your MdiChild forms should be declared globally in the MdiParent form and set to null when the MdiParent loads. On your parent form, label1 should have the public modifier set. Personally, I try to avoid "Protected", "Protected Internal", and "Internal" unless absolutely necessary. When calling your child form from the parent, first check that the form is not null, otherwise you are liable to destroy the form that someone is working on. If the form is not null, call "BringToFront()" or "Activate()". If the child form is null, instantiate and call it. Example: void ShowChild1() { if ((frmChild1 == null) || (frmChild1.IsDisposed == true)) { frmChild1 = new Child1Form(); frmChild1.MdiParent = this; frmChild1.WindowState = (ActiveMdiChild == null) ? FormWindowState.Maximized : ActiveMdiChild.WindowState; frmChild1.Show(); } mifrmChild1.Checked = true; if (ActiveControl != frmChild1) { frmChild1.BringToFront(); } } Now, your MdiChild form must be created in a way that it knows who its parent is. MyMdiForm _parent; public Child1Form(Form parent) { InitializeComponent(); _parent = (MyMdiForm)parent; } void SetParentText(string updateText) { _parent.label1.Text = updateText; } If you don't like setting the label1 modifier to public, you could always create properties to read and/or write to the label1 control. Here is how you could modify the MdiParent to have a ReadOnly label1 control without setting label1's modifier to public: public string Label1Text { set { label1.Text = value; } } Does this get you moving along in the right direction?
  22. Add a "KeyDown" event handler for your ListView control. This is by no means complete: bool _usedEnter = false; void p5_Why_KeyDown(object sender, KeyEventArgs e) { _usedEnter = false; if (e.KeyCode == Keys.Enter) { _usedEnter = true; // Enter Key was pressed. } } Basically, set an boolean value that you can then check in the ItemActivate event that you already have. Hope that helps!
  23. Try setting the form's Size and Location properties before showing the form. It is likely that those values are setting the form outside of the parent's viewable region.
  24. Not really a fan off Rubicashrama's message... Anyway, how did you get this to work? I don't have a need to do it, but it is something I would not have thought possible. I'd just like to see an example of how you did this.
  25. What could I do to monitor the Windows print queue? We have a Datamax label printing machine that creates serial numbers for our products. Occasionally, it is out of media, has a jam, is powered off, etc. In those cases, the serial number is lost. All I want to do is void a serial number in our database if the job I sent to the printer was unsuccessful. The printer is local and has the name "Datamax". The PC is running Windows XP. We are developing under Visual Studio 2005 Professional. The closest code examples I have found used a ManagementObjectCollection object, but they do not get into details on how to do what I need to accomplish. I'd like to avoid having to use specific SDK calls to the Datamax printer (if there is such a thing) because there has been talk about trying to find a more reliable printer. Thanks for any help, Joe
×
×
  • Create New...