2012-10-25 34 views
0

我想将我的代码分离出来,放到类文件中。然而,我遇到的问题是如何从类文件访问Form1中包含的dataGridviewLogging将数据适配器和gridview分离成一个类文件

public void getLogging(String sql) 
{ 
    SqlDataAdapter dataadapter = new SqlDataAdapter(sql, mycon);  
    DataSet ds = new DataSet(); 

    try 
    { 
     dataadapter.Fill(ds, "LOG_MESSAGE"); 
     dataGridViewLogging.DataSource = ds; 
     dataGridViewLogging.DataMember = "LOG_MESSAGE"; 
    } 
    catch (Exception f) 
    { 
     Console.WriteLine(f.ToString()); 
     MessageBox.Show("FAILURE:" + f.ToString()); 
     return; 
    } 
} 

我一直在想办法我可以做到这一点?想法?

+0

你不应该这样做。你的类应该拥有与页面布局无关的实体和抽象数据类型。 – AMember

回答

0

由于您的方法名为getLogging您想要返回可用作数据源的数据。因此,不要在此设置数据源,而应将其设置在可访问数据绑定控件的位置。

例如(在Form1中):

dataGridViewLogging.DataSource = getLogging(
      DateTime.Today.AddMonths(-6) 
     , DateTime.Today); // don't pass the sql directly, use parameters instead 

和类:

public DataSet getLogging(DateTime logFrom, DateTime logTo) 
{ 
    DataSet ds = new DataSet(); 
    const string sql = "SELECT Columns FROM dbo.Table WHERE LoggedAt BETWEEN @LoggedFrom AND @LoggedTo ... ODRER BY ..."; 
    using (var mycon = new SqlConnection(connectionString)) 
    using (var da = new SqlDataAdapter(sql, mycon)) 
    { 
     da.SelectCommand.Parameters.AddWithValue("@LoggedFrom", logFrom); 
     da.SelectCommand.Parameters.AddWithValue("@LoggedTo", logFrom); 
     try 
     { 
      da.Fill(ds); 
     } catch (Exception f) 
     { 
      // log here 
      throw; 
     } 
    } 
    return ds; 
} 
+0

该类没有返回数据集。退货声明在哪里? – user1158745

+0

@ user1158745:当然,相应地编辑我的答案。顺便说一句,如果你想用自定义参数进行过滤,可以使用'SqlParameters',这些参数的值可以作为参数添加到此方法中。这就是为什么我已经使sql字符串不变。参数也会阻止sql注入。 –

+0

@ user1158745:编辑我的答案以显示如何使用参数。 –

0

你可以做类似的三层体系结构..presentation,业务逻辑和数据访问。

Create a method or Function that take String as command Text, specify your command Type(SP,or inline command) 

用它将DataSet或DataTable作为返回对象。

Pubic DataTable GetDataTableFromDB(String CommandText,SqlCommandType type,SqlParameter [] param) 
{ 
    DataTable temp=somthing; 
    /* your logic */ 
    return DataTable; 
} 

以此作为类文件,并在你的Form1类或Form1.cs中获取你的数据集(如果你是C#蜜蜂)

有很大的时间,毕竟编码FUN !!!!!! !