private void button1_Click(object sender, EventArgs e)
{
new System.Threading.Thread(delegate()
{
Export();
}).Start();
}
private void Export()
{
int rowcount = ((System.Data.DataTable)this.dgResult.DataSource).Rows.Count;
System.Data.DataTable dt = (System.Data.DataTable)this.dgResult.DataSource;
if (rowcount > 0)
{
if (InvokeRequired)
{
BeginInvoke(new MethodInvoker(delegate()
{
svDialog.Filter = "Excel|*.xls";
svDialog.Title = "Save an Excel File";
svDialog.ShowDialog();
if (svDialog.FileName != "")
{
Business.ExportToExcel.ExcelFromDataTable(dt, svDialog.FileName);
MessageBox.Show("Export completed");
开发者_如何学JAVA }
}));
}
else
{
svDialog.Filter = "Excel|*.xls";
svDialog.Title = "Save an Excel File";
svDialog.ShowDialog();
if (svDialog.FileName != "")
{
Business.ExportToExcel.ExcelFromDataTable(dt, svDialog.FileName);
MessageBox.Show("Export completed");
}
}
}
else
{
MessageBox.Show("No data found");
}
}
when the button1 is clicked then export method is getting called in separate thread and no error raise but save file dialog is not getting error. so please tell me what is my mistake in the code. my approach is wrong to call a method in separate thread. also explain plzz save file dialog is not opening. which area i need to rectify. plzz explain. thanks.
Keep in your mind, that all Winforms object should be used from main UI thread. So in separate thread you MUST use Invoke/BeginInvoke. If you can, do all "Winforms stuff" in UI thread and after that run separate thread with all data/informations which is required.
I think, the better way is:
private void button1_Click(object sender, EventArgs e) {
this.Export();
}
private void Export() {
System.Data.DataTable dt = (System.Data.DataTable)this.dgResult.DataSource;
if ( dt.Rows.Count > 0 ) {
// initialize save file dialog
DialogResult rslt = this.svDialog.ShowDialog(this);
if ( rslt == DialogResult.OK ) {
string filePath = this.svDialog.FileName;
// QueueUserWorkItem runs target delegate in separate thread
ThreadPool.QueueUserWorkItem( (_state)=> this.Export(dt, filePath) );
}
}
else {
// ... some other code ....
}
}
private void Export(DataTable data, string filePath) {
Exception thrownException = null;
try { Business.ExportToExcel.ExcelFromDataTable(dt, filePath); }
catch( Exception exc ) { thrownException = exc; }
if ( null == thrownException ) { MsgBox("Export completed."); }
else { MsgBox("Error: " + thrownException.Message); }
}
private void MsgBox(string text) {
if (this.InvokeRequired) {
Action<string> dlg = this.MsgBox;
this.Invoke( dlg, text );
}
else {
MessageBox.Show(this, text);
}
}
精彩评论