如何调用方法多次点击按钮

本文关键字:按钮 方法 何调用 调用 | 更新日期: 2023-09-27 18:13:45

我有下面的代码,让我从一个excel表直接添加数据到一个给定的数据库,现在我想知道我如何能够多次调用该方法从两个不同的excel文件一次添加数据,这是一个按钮调用这个方法一旦点击,使用多线程。

private void AddToDatabase()
{
    using (OleDbConnection connection =
                new OleDbConnection(excelConnectionString))
    {
         connection.Open();
         CheckNumeberOfSheets(connection);
    }
}

按钮代码;

private void button1_Click(object sender, EventArgs e)
{
    AddToDatabase();
}

如何调用方法多次点击按钮

也许你可以传递一个字符串给你的方法addtodatabase,如

   private void AddToDatabase(string fileName){
    if(fileName.Equals("yourfirstFile"))
     {
      using (OleDbConnection connection =
            new OleDbConnection(excelConnectionString))
            {
                connection.Open();
                CheckNumeberOfSheets(connection);
            }
      }
    else if(fileName.Equals("yoursecondfile"))
     {
      using (OleDbConnection connection =
            new OleDbConnection(excelConnectionString2))
            {
                connection.Open();
                CheckNumeberOfSheets(connection);
            }
      }
    }

然后这样命名

    private void button1_Click(object sender, EventArgs e)
    {
         AddToDatabase("yourfirstFile");
         AddToDatabase("yoursecondFile");
    }

第一步:创建一个名为"ClassFiles"的类

public class ClassFiles
{
private String fileName;
private String excelConnectionString;

public String getFileName()
 return fileName;
public void setFileName(String fileName)
{
 this.fileName=fileName;
}
public String getExcelConnectionString()
 return excelConnectionString;
public void setExcelConnectionString(String excelConnectionString)
{
 this.excelConnectionString=excelConnectionString;
}
}

步骤2:在主类中,添加fileName和excelConnection字符串,如:

public class MainClass{

private void AddFilesToDB(List<ClassFiles>fileDetails){
  for(ClassFiles fileDeteil : fileDetails){
            using (OleDbConnection connection =
            new OleDbConnection(fileDeteil.getExcelConnectionString))
            {
                connection.Open();
                CheckNumeberOfSheets(connection);
            }
  // as well as u can get the file name..
           String fileName=fileDeteil.getFileName();
    }
}
public Static void main(string args[]){
    List<ClassFiles> addDetails =new ArrayList<ClassFiles>();
    //now add the no of files into the list
     ClassFiles objFile1=new ClassFiles();
     objFile1.setFileName("filename1");
     objFile1.setExcelConnectionString("excelConnectionString1");
     addDetails.add(objFile1);
     ClassFiles objFile2=new ClassFiles();
     objFile2.setFileName("filename2");
     objFile2.setExcelConnectionString("excelConnectionString2");
     addDetails.add(objFile2);
     and so on..
     then call the function for further process.,
    new MainClass().AddFilesToDB(addDetails);
  }

hope it ll help you..