如何解决如果显示消息框,则暂停c#wpf应用程序中该函数的其余执行
我有以下方法为用户浏览文件。
public void BrowseFile(TextBox filanametextbox,TextBlock textblocname,DataGrid datagrid,Button browsebutton,Button loadbutton)
{
// Create OpenFileDialog
OpenFileDialog openFileDlg = new OpenFileDialog();
// Launch OpenFileDialog by calling ShowDialog method
Nullable<bool> result = openFileDlg.ShowDialog();
// Get the selected file name and display in a TextBox.
// Load content of file in a TextBlock
if (result == true)
{
filanametextbox.Text = openFileDlg.FileName;
textblocname.Text = "Created on: " + File.GetCreationTime(openFileDlg.FileName).ToString() + "\n";
//Debug.WriteLine(File.GetCreationTime(openFileDlg.FileName).ToString());
var datatablematrix = ConvertToDataTable(filePath: openFileDlg.FileName);
if (browsebutton.Name.ToString()=="BrowseButton")
{
if (!filanametextbox.Text.Contains("Files.csv"))
{
MessageBox.Show("The file imported is an invalid format file! \n Please check that you have imported the correct one.","Warning",MessageBoxButton.OK,MessageBoxImage.Exclamation);
}
}
else if (browsebutton.Name.ToString()=="BrowseButtonLayout")
{
if (!filanametextbox.Text.Contains("Layout.csv"))
{
MessageBox.Show("The file imported is an invalid layout file! \n Please check that you have imported the correct one.",MessageBoxImage.Exclamation);
}
}
else if (browsebutton.Name.ToString() == "BrowseButtonBC")
{
if (!filanametextbox.Text.Contains("BusinessChecks.csv"))
{
MessageBox.Show("The file imported is an invalid business checks file! \n Please check that you have imported the correct one.",MessageBoxImage.Exclamation);
}
}
datagrid.DataContext = datatablematrix.DefaultView;
}
// Set filter for file extension and default file extension
openFileDlg.DefaultExt = ".txt";
openFileDlg.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
// Set initial directory
openFileDlg.InitialDirectory = @"C:\Documents\";
// Multiple selection with all file types
openFileDlg.Multiselect = true;
browsebutton.IsEnabled = true;
loadbutton.IsEnabled = true;
}
我想以某种方式是由三个if语句之一触发消息框以中止该函数其余部分的执行。这意味着不会填充数据表,也不会启用loadbutton。
应用的初始状态
消息框上的状态
当用户将在消息框上单击“确定”时,我希望仍禁用“加载”按钮,并且数据网格表(黑盒)未填充值。
在网上搜索时,我发现了一个SO问题,该问题主张创建布尔函数。虽然,我不太确定如何在我的单个函数中嵌入this解决方案。
解决方法
我想通过某种方式触发消息框时 三个if语句可停止其余的执行 功能。
如果要停止在c#中进一步执行某个函数,可以使用return;
,它退出当前函数,而无需执行任何其他代码。
private bool ExampleVoid() {
MessageBox.Show("The file imported is an invalid layout file! \n Please check that
+ you have imported the correct one.","Warning",MessageBoxButton.OK,MessageBoxImage.Exclamation);
// Return out of function because an error happened
return;
}
请注意,如果您的函数返回某些信息(例如布尔值),则需要在返回语句中添加相应的值。如果是布尔函数,则为false或true。
示例:
private bool ExampleBool() {
// Halt Execution of Function and return out of it
return false;
// Code Below the return statement is not executed
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。