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

时间:2013-05-15 10:41:38

标签: c# multithreading

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

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

按钮代码;

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

2 个答案:

答案 0 :(得分:1)

可以将字符串传递给方法AddToDatabse,如

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

答案 1 :(得分:0)

第1步:创建一个名为“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..