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

时间:2016-01-20 04:53:14

标签: c# c#-4.0 inputbox

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

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);
    }
}

1 个答案:

答案 0 :(得分:1)

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

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; 或者在属性框中设置它,如果你总是有Multiselect那么。

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

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
       }





    }