C# 输入框取消按钮不起作用

C# Inputbox cancel button does not work

我的浏览按钮上有以下代码。 如何为输入框取消按钮编写代码。

private void btnbrowse_Click(object sender, EventArgs e)
{
    String sf_no = Microsoft.VisualBasic.Interaction.InputBox(
        "You are uploading File For SF NO. ", "Information", def, -1, -1);

    ofd.ShowDialog();
    ofd.Multiselect = true;
    string[] result = ofd.FileNames;

    foreach (string y in result)
    {
        String path = y.Substring(0, y.LastIndexOf("\"));
        String filename = y.Substring(y.LastIndexOf("\"));
        string[] row = new string[] { sf_no,path, filename };
        dataGridView2.Rows.Add(row);
    }
}

取消 InputBox 时,return 值为空字符串,因此您的代码为

if (sf_no!="")
{
//ok stuff here, including the showdialog logic as shown below
}
{
//cancel stuff here
}

因为ofd.ShowDialog也可以取消你的代码应该是:

if (ofd.ShowDialog()==DialogResult.OK)
{ 
//do stuff on OK button 
}
else 
{
//do stuff on Cancel button
}

在 调用 ShowDialog() 之前调用 ofd.Multiselect = true; 或在属性框中设置它,如果你总是有多选的话。

因此,您的新代码现在是:

private void btnbrowse_Click(object sender, EventArgs e)
    {

       String sf_no = Microsoft.VisualBasic.Interaction.InputBox("You are uploading File For SF NO. ", "Information", def, -1, -1);

       if (sf_no!="") //we got the sf_no
       {
           ofd.Multiselect = true;
           if (ofd.ShowDialog()==DialogResult.OK)//user select file(s)
           {

                string[] result = ofd.FileNames;          

                foreach (string y in result)
                {

                  String path = System.IO.Path.GetDirectoryName(y);
                  String filename = System.IO.Path.GetFileName(y);
                  string[] row = new string[] { sf_no,path, filename };
                  dataGridView2.Rows.Add(row);
                 }
           }
           else
           {
           //handle what happen if user click cancel while selecting file  
           }
       }
       else
       {
       //handle what happen if user click cancel while entering SF NO
       }





    }