For smart Primates & ROBOTS (oh and ALIENS ).

Showing posts with label winform. Show all posts
Showing posts with label winform. Show all posts

Wednesday, April 22, 2015

File open Dialogbox show error System Threading ThreadStateException

Problem:

I am wondering when you get the error 'System.Threading.ThreadStateException' while using OpenFileDialog in C# Winform application. So how to solve this?

First we see the error details, after that I will show you solution.
See the screenshot below.
System.Threading.ThreadStateException



















Error is:
"An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll
Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process."

Code is:

System.Windows.Forms.OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Select HTML/HTML5 file";
openFileDialog.InitialDirectory = "C:";
openFileDialog.Filter = "HTML files (*.html)|*.html|Flv files (*.htm)|*.htm";
openFileDialog.AutoUpgradeEnabled = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
String Chosen_File = openFileDialog.FileName;
       String inputExt = (Path.GetExtension(Chosen_File).ToLower());
       textBox1.Text = Chosen_File;
       textBox2.Text = Chosen_File + "_New" + inputExt;
}
It will show error on the line

if (openFileDialog.ShowDialog() == DialogResult.OK)


The full error code is:
=============================
System.Threading.ThreadStateException was unhandled
  HResult=-2146233056
  Message=Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.FileDialog.RunDialog(IntPtr hWndOwner)
       at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.CommonDialog.ShowDialog()
       at CoreRenderer.Form1.button3_Click(Object sender, EventArgs e) in d:\CurrentProject\WinForm\VS2013Testing\CS\CoreRenderer\CoreRenderer\Form1.cs:line 121
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at CoreRenderer.Program.Main() in d:\CurrentProject\WinForm\VS2013Testing\CS\CoreRenderer\CoreRenderer\Program.cs:line 21
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
=============================

Solution:

To overcome this problem you need to use Thread class. See below code that how to fix this error.

Example:

Create a method as below:
public void getfile() {
      System.Windows.Forms.OpenFileDialog openFileDialogAvi = new OpenFileDialog();
      openFileDialogAvi.Title = "Select HTML/HTML5 file";
      openFileDialogAvi.InitialDirectory = "C:";
      openFileDialogAvi.Filter = "HTML files (*.html)|*.html|Flv files (*.htm)|*.htm";
      openFileDialogAvi.AutoUpgradeEnabled = true;
      if (openFileDialogAvi.ShowDialog() == DialogResult.OK)
      {
         String Chosen_File = openFileDialogAvi.FileName;
         String inputExt = (Path.GetExtension(Chosen_File).ToLower());
         Invoke((MethodInvoker)delegate
         {
               textBox1.Text = Chosen_File;
               textBox2.Text = Chosen_File + "_New" + inputExt;
         });
      }
   }


On click button access the above method:

private void button2_Click(object sender, EventArgs e) {
       Thread threadGetFile = new Thread(new ThreadStart(getfile));
       threadGetFile.ApartmentState = ApartmentState.STA;
       threadGetFile.Start();         
}

Share:

Monday, March 23, 2015

Text to speech

Text to speech



Text to speech












Download here:
Download











Share:

Thursday, March 12, 2015

Cell align top in dataGridView in c#

Use one line code as below:

dataGridView1.Columns["Question"].DefaultCellStyle.Alignment=DataGridViewContentAlignment.TopLeft;
Share:

Get Volume Serial Number of Drive in C#

Listed below the code use in your project to get Volume serial number

//let's show C drive's volume serial number
String d = "c";
try {
    System.Management.ManagementObject dsk1 = new System.Management.ManagementObject(@"win32_logicaldisk.deviceid=""" + d + @":""");
    dsk1.Get();
    string s1 = dsk1["VolumeSerialNumber"].ToString();
    MessageBox.Show(s1);
}
catch (Exception ee)
{
    MessageBox.Show(ee.ToString());

}
Share:

SEND EMAIL FROM WINFORM

Some times you want to open microsoft outlook from microsoft winform and then type the mail message and send it. use below one line of code.


System.Diagnostics.Process.Start("mailto:XYZ@XYZ.COM");
Share:

SHOW FORM WITH IN FORM AS IMAGE


Problem:

Some time you have already created many form. then are opening separately when you click on any button in MDI Form or separate in C# winform.  After soe time requirement has changed. the new requirement is to open new form in the same form from where you are clicking button.
For better understand see below image

Show Form with in form as image

















Solution:


Use panel control to show form 


Example:

panel1.Visible = true;
panel1.Controls.Clear();
StandardTest f1 = new StandardTest(); // this the form which you want to show
f1.TopLevel = false;
panel1.Controls.Add(f1);
panel1.Width = 1100;
panel1.Height = 620;
f1.Width = 1100;
f1.Height = panel1.Height - 0;
f1.Dock = DockStyle.Left;
f1.Show();



Share:

Friday, September 19, 2014

Load image in picturebox in C#

Load image in picturebox in C#

How to load image in picturebox in dot net C# winform, Listed below code will solve your problem.


pictureBox1.Image = System.Drawing.Image.FromFile("ImageNameWithFullPath");

Share:

Tuesday, July 08, 2014

Sum datagridview cell by button click c#

If you have enter many records in datagridview in c# winform and want to show the sum of any cell values for example: "mark" cell, then you needed to retrieve each datagridview row and add it's value in other variable.... but we want to do this not using iteration.. thwn what we will do?

Use listed below code to achieve target:

---------------------------------------------------------------------------------------------------
string m = "Total Marks =" + dataGridView1.Rows.Cast<DataGridViewRow>().AsEnumerable()                                                    .Sum(x => int.Parse(x.Cells["mark"].Value.ToString())).ToString();
---------------------------------------------------------------------------------------------------


Share:

Sort Datagridview column by button click c#

Sort Datagridview column by button click c#

If you have added the random records in your Datagridview C# winform and want to show records by any column on button click then use this:

-------------------------------------------------------------------------------------
dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);
-------------------------------------------------------------------------------------
OR
-------------------------------------------------------------------------------------
dataGridView1.Sort(dataGridView1.Columns["mark"], ListSortDirection.Ascending);
-------------------------------------------------------------------------------------

"mark" is the cell name in the datagridview.


Share:

Saturday, July 05, 2014

Send Files to IP address in C#

If there are you situation you want to send file to IP address,
then use listed below code:

string sourceDir = @"C:\\tt";
string destIP = @"\\10.10.10.10\shared-folder-amit";
string[] sourceFiles = Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories);
foreach (string files in sourceFiles) {
  string localFile = files.Replace(sourceDir, "");
  if (!Directory.Exists(Path.GetDirectoryName(destIP + "\\" + localFile)))
    Directory.CreateDirectory(Path.GetDirectoryName(destIP + "\\" + localFile));
  File.Copy(files, destIP + "\\" + localFile, true);
}



Share:

selected check box record from DataGridView c# winform

Suppose you have a DataGridView with the check box. Data are showing and you want to store only those data that's check boxes is selected, so what you will do? In simple you will use the loop which will retrieve all data from DataGridView from first row to last row and in that loop check the condition is which rows’s check box is selected.

It is a good way but not a smart way, imagine that there are 99999999 rows in the DataGridview and only 100 rows are selected.

Smart way is only create a loop which iterate only 100 times not for 99999999 times.

The Smart way is listed below:
1) Assume that we have the DataGridView with records and also have the check box and its name is "selectMe".

2) use listed below code to retrieve only selected checkboxes.

List<DataGridViewRow> list = dataGridView1.Rows.Cast<DataGridViewRow>().Where(eachrow => Convert.ToBoolean(eachrow.Cells["selectMe"].Value) == true).ToList();
foreach (var row in list) {
    MessageBox.Show(row.Cells["emp_id"].Value.ToString());
}
Share:

Thursday, May 22, 2014

Child form open and close problem in MDIForm C#

Child form open and close problem in MDIForm C#

===================================================================================
You have a menu item in MDIForm, after clicking on that a child form will be shown.
If you close the child form by clicking in cross "X" button which is on
right top corner, the child form will be closed.
And if you again click on MDIForm's menu item then the child form will not show.
This is because child form is disposed but that's variable is not null.
Listed below the code is the good example of that problem:
-----------------------------------------------------------------------------------
namespace MyProject
{
    public partial class AdminMDIParent : Form
    {
        Synopsis synopsis=null;
    }

    private void ShowNewForm(object sender, EventArgs e)
        {
            if (synopsis == null)
                {
                    synopsis = new Synopsis();
                    synopsis.MdiParent = this;

        }
              synopsis.Show();
              synopsis.Focus();
        }

}
-----------------------------------------------------------------------------------
The above code will not show the form in second time and rest. This is because the "synopsis"
is the object of "Synopsis" Form class. and this is the local variable of AdminMDIParent" class.
Only first time that code will work. So how to overcome this problem?
by the way, You will just use this code:
private void ShowNewForm(object sender, EventArgs e)
{
    synopsis = new Synopsis();
        synopsis.MdiParent = this;
    synopsis.Show();
        synopsis.Focus();
}
But the problem is when you use the above code and click again and again MDIForm's menu item without
closing child form; the multiple child form will be shown.
-----------------------------------------------------------------------------------

So to overcome this problem; we check its "visible" property as listed below.  Listed below code work fine.
private void ShowNewForm(object sender, EventArgs e)
{
    if (synopsis == null || synopsis.Visible==false)
    {
        synopsis = new Synopsis();
        synopsis.MdiParent = this;
    }
        synopsis.Show();
        synopsis.Focus();
}
-----------------------------------------------------------------------------------
Share:

Ads Inside Post

Powered by Blogger.

Archive