无法返回数据表

时间:2010-10-19 22:21:11

标签: c# excel csv checkbox datagridview

public DataTable ExcelToDatatable_dt1  
{
    get  
    {  
        foreach (GridViewRow rowItem in GridView1.Rows)  
        {  
            CheckBox chk;  
            // gets the Debit Reference number for each row checked  
            string productId = GridView1.DataKeys[rowItem.RowIndex].Value.ToString();  
           chk = (CheckBox)(rowItem.Cells[0].FindControl("RowChecker"));  
           if (chk.Checked)  

           {  
               string fileName = Session["fileName"].ToString();  
               //string fileName = "Collection.csv";  
               // put the file name here  
               string strSql = "SELECT * FROM [" + fileName + "] WHERE DDIREF = ["+ productId +]";  
               string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(".\\Files\\") + ";" + "Extended Properties='text;HDR=YES;'";  


               using (FileStream filestr = new FileStream(Server.MapPath(".\\Files\\") + "\\schema.ini",  
                   FileMode.Create, FileAccess.Write))  
               {  
                   using (StreamWriter writer = new StreamWriter(filestr))  
                   {  
                       writer.WriteLine("[" + fileName + "]");  
                       writer.WriteLine("ColNameHeader=False");  
                       writer.WriteLine("Format=CSVDelimited");  
                       writer.WriteLine("DateTimeFormat=dd-MMM-yy");  

                       //Message_ltr.Text += positionList[0].ToString();  

                       for (int i = 0; i < 29; i++)  
                           //if (((positionList[i].ToString() != null) && (positionList[i].ToString() != "")) && ((nameList[i].ToString() != null) && (nameList[i].ToString() != "")))  
                           writer.WriteLine("Col" + positionList[i].ToString() + "=" + nameList[i].ToString() + " Text Width 100");  
                       //writer.WriteLine("Col2=SortCode Text Width 30");  

                       writer.Close();  
                       writer.Dispose();  
                   }  
                   filestr.Close();  
                   filestr.Dispose();  
               }  


               OleDbDataAdapter oleda = new OleDbDataAdapter(strSql, strCSVConnString);  
               DataTable dtbCSV = new DataTable();  
               oleda.Fill(dtbCSV);  

               return dtbCSV;  
           }  

        }  

        return null;// instead of null I want to return dtbCSV here  
        }  

这会产生错误

  

“错误45'DirectDebit.Interbacs.CompanyUpload.ExcelToDatatable_dt1.get':并非所有代码路径都返回值”。

错误是由于return语句不在正确的范围内。但问题是,我想返回dtbCSV并且我无法在“获取”范围内返回,因为在get上下文中不存在dtCSV,我不知道在返回方法中的范围之间传递值。

1 个答案:

答案 0 :(得分:0)

尝试将DataTable dtbCSV = new DataTable();放在foreach声明之前(并删除其他声明)。

修改
注意:这会将dtbCSV置于整个get块的范围内,而不仅仅放在if语句中。