2014-02-10 23 views
1

我正在开发一个应用程序使用Winforms和C#。我有一个类将获取一个表的主数据。该类中的函数执行返回2列数据的存储过程。发送数据从类到winform

我有一个窗体,它有一个ListBox控件,TextBox和ComboBox。我想:

  • 在列表框中显示列1的整个数据。
  • 显示列1选择行上的文本框中的行值和组合框中的第2列值。值的更改基于Listbox中的选择更改。

代码使用存储过程来获取数据:

public void GetDeity() 
{ 
     cmd = new SqlCommand(); 
     cmd.Connection = conDB; 
     cmd.CommandType = System.Data.CommandType.StoredProcedure; 
     cmd.CommandText = "get_DeityMaster"; 
     cmd.ExecuteNonQuery(); 

     return; 
} 

ListBox Name: lstDeityList 
TextBox Name: txtDeityName 
ComboBox Name: cmbDeityCategoryName 

请有关如何将数据传递帮助。谢谢

回答

1

你需要从你的方法返回数据如下,目前你的方法什么都不返回。

,你可能需要改变方法实现返回数据表或数据集

public DataTable GetDeity() 
{ 
    using(SqlConnection sqlConn = new SqlConnection(conSTR)) 
    using(SqlCommand cmd = new SqlCommand("get_DeityMaster", sqlConn)) 
    { 
     cmd.CommandType = System.Data.CommandType.StoredProcedure; 
     sqlConn.Open(); 
     DataTable dt = new DataTable(); 
     dt.Load(cmd.ExecuteReader()); 
     return dt; 
    } 
} 

现在你可以使用返回的DataTable以上,当选择项改变事件绑定Listbox控制可以绑定其他文本框和组合框。

在窗体

你可以像创建类的对象下面

Yourclass obj = new Yourclass(); 
DataTable dt= obj.GetDeity(); 

ListBox1.DataSource = dt; 
ListBox1.DisplayMember = "Column1Name"; 
ListBox1.ValueMember = "Column2Name"; 

您需要添加SelectedIndexChanged事件为ListBox

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e) 
{ 
    TextBox1.Text = ((DataRowView)ListBox1.SelectedItem).Row.ItemArray[0].ToString(); 
    // bind the ComboBox as well 
} 
+0

谢谢Damith,这很整洁。你可以请指导我如何抓住表格侧的dt并绑定到控件。非常感谢 – Rajiv

+0

谢谢,我试过使用下面,但它似乎不连接到数据库。 DB是好的: using(conDB = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings [“SRKBS-PB”])) cmd = new SqlCommand(“sp_GetDeity”,conDB); cmd.CommandType = System.Data.CommandType.StoredProcedure; DataTable dt = new DataTable(); dt.Load(cmd.ExecuteReader()); return dt; } – Rajiv

0

你为什么不持有调用类的方法在数据表中提取数据。然后将该数据表的列分配给您喜欢的不同控件。

例如

public void GetData() 
     { 
      DataTable odt = new DataTable(); 
      odt = obj.GetDeity(); 

      Combobox.DataSource = odt; 
      .......... set other controls also... 
     } 

public DataTable GetDeity() 
     { 

      SqlCommand cmd = new SqlCommand("get_DeityMaster"); 
      cmd.CommandType = CommandType.StoredProcedure; 
      return getdatatable(cmd); // YOUR DATA FETCHING LOGIC 
     } 
1

将函数的返回类型从void更改为DataTable。用你的命令创建SQLAdapter并填写DataTable

public DataTable GetDeity() 
{ 
DataTable mTable = new DataTable(); 

cmd = new SqlCommand(); 
cmd.Connection = conDB; 
cmd.CommandType = System.Data.CommandType.StoredProcedure; 
cmd.CommandText = "get_DeityMaster"; 

SqlAapter mAdapter = new SqlAdapter(cmd); 
mAdapter.Fill(mTable); 

return mTable 
}