2016-10-03 38 views
0

我對C#非常新,所以請原諒我的無知。我有一個SQL Server表,我試圖從該表中將選擇查詢結果轉換爲C#中的表單組合框。C#從SQL Server數據庫獲取結果,通過類顯示在組合框中

我在試圖做的是創建一個類,它將在數據庫端執行一個存儲過程,而我的絆腳石是如何將該類整合到代碼中,以便結果顯示在C#中的下拉列表中。

這是我到目前爲止在C#中的。非常感謝您的幫助。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Data; 
using System.Data.SqlClient; 
using System.Configuration; 

namespace MedicalOffice 
{ 
    public class DBAIdSelect 
    { 
     public void SelectPractice() 
     { 
      using (SqlConnection cn = new SqlConnection()) 
      { 
       cn.ConnectionString = GetConnectionString(); 
       cn.Open(); 

       using (SqlCommand cmd = new SqlCommand("SelectPracticeID")) 
       { 
        cmd.Connection = cn; 
        cmd.CommandType = CommandType.StoredProcedure; 
        cmd.ExecuteNonQuery(); 
       } 
      } 
     } 

     private string GetConnectionString() 
     { 
      string conString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; 
      return conString; 
     } 
    } 
} 

SQL Server表:

SET ANSI_NULLS ON 
SET QUOTED_IDENTIFIER ON 
SET ANSI_PADDING ON 
GO 

CREATE TABLE [dbo].[Practices] 
(
    [PracticeID] [int] IDENTITY(1,1) NOT NULL, 
    [PracticeName] [varchar](50) NULL, 
    [Address1] [varchar](50) NULL, 
    [Address2] [varchar](50) NULL, 
    [City] [varchar](50) NULL, 
    [State] [char](2) NULL, 
    [Zip] [varchar](10) NULL, 
    [IsActive] [bit] NULL, 
    [DateCreated] [date] NULL 
     CONSTRAINT [DF_Practices_DateCreated] DEFAULT (getdate()), 
    [CreatedBy] [int] NULL, 
    [DateModified] [date] NULL, 
    [DateModifiedBy] [int] NULL, 

    CONSTRAINT [PK_Practices] 
     PRIMARY KEY CLUSTERED ([PracticeID] ASC) 
       WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
         IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
         ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 
GO 

SET ANSI_PADDING OFF 
GO 

和存儲過程:

create proc [dbo].[SelectPracticeID] 
as 
    select PracticeID 
    from dbo.Practices 
GO 
+4

您沒有提問?但你的下一步將是從你的班級返回值。 'cmd.ExecuteNonQuery();'不會工作 - 您需要返回值。 – Jonesopolis

+1

Webforms,winforms,MVC,WCF?你使用什麼技術? – Liam

+1

您調用存儲來檢索記錄,但您沒有對返回進行任何操作。例如,如果你得到一個datareader,你應該從那裏讀取記錄。連接也沒有關閉。網上有很多關於如何實現你想要實現的代碼示例。 – derloopkat

回答

2

,每當你想調用存儲過程可以使用這個類,它返回一個DataTable

class myclass 
{ 
    public DataTable SelectData(string proc, SqlParameter[] param) 
    { 
      DataTable Table = new DataTable(); 
      SqlCommand Cmd = new SqlCommand(); 
      Cmd.CommandType = CommandType.StoredProcedure; 
      Cmd.CommandText = proc; 
      Cmd.Connection = Acces.Connection; 

      if (param != null) 
       for (int i = 0; i < param.Length; i++) 
       { 
        Cmd.Parameters.Add(param[i]); 
       } 

      SqlDataAdapter Adapter = new SqlDataAdapter(Cmd); 
      Adapter.Fill(Table); 

      return Table; 
     } 
    } 

所以每當你要使用的任何存儲過程返回結果集,使用它,如果你要執行任何數據:

public void ExecuteData(string proc, SqlParameter[] param) 
{ 
    SqlCommand Cmd = new SqlCommand(); 
    Cmd.CommandType = CommandType.StoredProcedure; 
    Cmd.CommandText = proc; 
    Cmd.Connection = Acces.Connection; 

    if (param != null) 
    { 
     Cmd.Parameters.AddRange(param); 
    } 

    Cmd.ExecuteNonQuery(); 
} 

讓你們班這兩個功能,每當你想調用類回到你一些數據或執行類似插入,更新,刪除一些數據...

你只需要調用

function("Stored_Proc_Name", Parameters); 

例子:

我想你們這樣一個選擇的過程:

myclass classs = new myclass(); 
    DataTable Table = new DataTable(); 
    Table = classs.SelectData("SelectPracticeID",null); //=cause there is no paramters in your stored proc 

所以Table將持有已被你的數據庫發送完整的信息

+0

就個人而言,我不是Untyped(又名「鬆散」)DataTables和DataSet的粉絲。 – granadaCoder

0

我建議建立DTO的/簡單波科對您的數據。

這種「方式」需要更多的努力......但是你的對象模型將會乾淨,漂亮和可維護。

2003年DataTables很好,現在不再是2003年了。下面是「窮人的ORM」,但很容易就可以遷移到實體框架或NHibernate中。 Datatables,Datasets,特別是未定義的數據集,不易遷移。

[Serializable] 
public partial class Practice 
{ 
    public int PracticeKey { get; set; }     
    public string PracticeName { get; set; }     
} 

[Serializable] 
public class PracticeCollection : ICollection<Practice> 
{ 
} 

internal static class PracticeDefaultLayout 
{ 
    public static readonly int PRACTICE_KEY = 0; 
    public static readonly int PRACTICENAME = 1; 

} 


public class PracticeSerializer 
{ 

    public PracticeCollection SerializeCollection(IDataReader dataReader) 
    { 
     Practice item = new Practice(); 
     PracticeCollection returnCollection = new PracticeCollection(); 
     try 
     { 

      int fc = dataReader.FieldCount;//just an FYI value 

      int counter = 0;//just an fyi of the number of rows 

      while (dataReader.Read()) 
      { 

       if (!(dataReader.IsDBNull(PracticeSearchResultsLayouts.PRACTICE_KEY))) 
       { 
        item = new Practice() { PracticeKey = dataReader.GetInt32(PracticeSearchResultsLayouts.PRACTICE_KEY) }; 

        if (!(dataReader.IsDBNull(PracticeSearchResultsLayouts.PRACTICENAME))) 
        { 
         item.PracticeName = dataReader.GetString(PracticeSearchResultsLayouts.PRACTICENAME); 
        } 


        returnCollection.Add(item); 
       } 

       counter++; 
      } 

      return returnCollection; 

     } 
     //no catch here... see http://blogs.msdn.com/brada/archive/2004/12/03/274718.aspx 
     finally 
     { 
      if (!((dataReader == null))) 
      { 
       try 
       { 
        dataReader.Close(); /* very important */ /* note, if your datareader had MULTIPLE resultsets, you would not close it here */ 
       } 
       catch 
       { 
       } 
      } 
     } 
    } 
} 








namespace MedicalOffice 
{ 
    public class PracticeDataLayer 
    { 
     public ICollection<Practice> GetAllPractices() 
     { 
      using (SqlConnection cn = new SqlConnection()) 
      { 
       cn.ConnectionString = GetConnectionString(); 
       cn.Open(); 

       using (SqlCommand cmd = new SqlCommand("SelectPracticeID")) 
       { 
        cmd.Connection = cn; 
        cmd.CommandType = CommandType.StoredProcedure; 
        IDataReader idr = cmd.ExecuteReader(); 
        return new PracticeSerializer().SerializeCollection(idr); 
        //// idr.Close(); /* very important, currently the serializer closes it..so commented out here */ /* note, if your datareader had MULTIPLE resultsets, you would close the datareader AFTER you used all the resultsets */ 
       } 
      } 
     } 

     private string GetConnectionString() 
     { 
      string conString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; 
      return conString; 
     } 
    } 
} 
相關問題