2013-11-26 33 views
0

我可能用错误的方法来处理这个问题。当我使用数据访问层技术时,我无法检索数据。如果我在主类使用下面的代码它的工作原理:当我使用数据访问层技术数据集和适配器时,无法检索数据

private void button1_Click(object sender, RoutedEventArgs e) 
{ 
    myCon.connectionString(); 
    string SomeString = string.Empty; 

    SomeString = "SELECT * FROM TableA"; 
    SqlCommand cmd = new SqlCommand(SomeString, myCon.Con); 
    adapter = new SqlDataAdapter(cmd); 
    ds = new DataSet(); 
    adapter.Fill(ds, "TableA"); 

    txtID.Text = ds.Tables[0].Rows[rno][0].ToString(); 
    txtFirstName.Text = ds.Tables[0].Rows[rno][1].ToString(); 
    txtLastName.Text = ds.Tables[0].Rows[rno][2].ToString(); 
} 

如果我放在其他类上面的代码我无法检索数据并没有错误。

ClassA的:

public void Button(string id, string firstname, string lastname) 
{ 
    myCon.connectionString(); 
    string SomeString = string.Empty; 

    SqlConnection cnn = myCon.Con; 

    cnn.Open();   

    CmdString = "SELECT * FROM TableA"; 
    SqlCommand cmd = new SqlCommand(CmdString, cnn.Con); 
    adapter = new SqlDataAdapter(cmd); 
    ds = new DataSet(); 
    adapter.Fill(ds, "Table"); 

    id = ds.Tables[0].Rows[rno][0].ToString(); 
    firstname = ds.Tables[0].Rows[rno][1].ToString(); 
    lastname = ds.Tables[0].Rows[rno][2].ToString(); 
} 

主要类:提前

public partial class MainWindow : Window 
{ 
    ClassA objs = new ClassA(); 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     objs.Button(txtID.Text, txtFirstName.Text, txtLastName.Text); 
    } 

感谢如果有人能帮助我在这里。

+1

您正在传递字符串的副本作为参数,而不是字符串本身。我还建议使用绑定而不是显式赋值。 – Somedust

回答

0

您是否试图通过您致电objs.Button来设置txtID.TexttxtFirstName.Text等的值?

这是一个有趣的方法,但由于传递参数的方式,它不会像写入那样工作。当你改变一个字符串变量的值时,你并没有改变这个变量本身,而是给它分配了一个全新的字符串。因此,当您在例程中重新分配参数时,您不再指向控件的.Text属性,而是指向不同的字符串。 .Text属性保持不变。

周围有此几种方法,但最简单的可能是改变你的子程序的签名:

public void Button(TextBox textId, TextBox txtFirstname, TextBox txtLastname) 
    { 

     myCon.connectionString(); 
     string SomeString = string.Empty; 

     SqlConnection cnn = myCon.Con; 


     cnn.Open(); 
     { 

     CmdString = "SELECT * FROM TableA"; 
     SqlCommand cmd = new SqlCommand(CmdString, cnn.Con); 
     adapter = new SqlDataAdapter(cmd); 
     ds = new DataSet(); 
     adapter.Fill(ds, "Table"); 

     txtId.Text = ds.Tables[0].Rows[rno][0].ToString(); 
     txtFirstname.Text = ds.Tables[0].Rows[rno][1].ToString(); 
     txtLastname.Text = ds.Tables[0].Rows[rno][2].ToString(); 
     } 

} 

其他选项是让你的输入参数,经过一系列的out参数。您也可以使其与ref关键字一起使用,但我不确定。