2013-04-02 16 views
0

我想在sqlserver2008中綁定數據庫的清單框。我正在用戶控制模塊上的asp.net C#中工作。我寫了一個代碼。我想知道代碼是否是perfact,也想知道在哪個事件中,我應該放置此代碼以獲得正確的輸出。對於SQL Server使用SqlServerDatabase綁定清單框

{ 
    int Post_Id = int.Parse(ViewState["ID"].ToString()); 
    SqlConnection cn1 = new SqlConnection(); 
    cn1.ConnectionString= 
    ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString; 
    SqlDataAdapter da = new SqlDataAdapter("SelectTags", cn1); 
    DataTable ds = new DataTable(); 
    SqlCommand cmnd1 = new SqlCommand("SelectTags", cn1); 
    cmnd1.Parameters.AddWithValue("@Post_Id",Post_Id); 
    cmnd1.CommandType = CommandType.StoredProcedure; 
    cn1.Open(); 
    cmnd1.ExecuteNonQuery(); 
    da.Fill(ds); 
    cn1.Close(); 
    foreach (DataRow dr in ds.Rows) 
    { 
     String field1 = dr["Tag_Name"].ToString(); 
     CheckBoxList2.Items.Add(field1); 
     CheckBoxList2.DataBind(); 
    } 
} 

SQL查詢2008

GO 
/****** Object: StoredProcedure [dbo].[InsertPost2Tag] Script Date: 04/02/2013 09:47:01 ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
Alter PROCEDURE [dbo].[SelectTags] 
    -- Add the parameters for the stored procedure here 
@Post_Id int 
AS 
BEGIN 

    SELECT mst_Tag.Tag_Name FROM mst_Tag INNER JOIN Post2Tag ON mst_Tag.tagId = Post2Tag.Tag_Id Where [email protected]_Id 

END 
GO 

回答

0

不需要做任何事情只需選中數據源爲檢查列表框,並在選定索引更改事件中將網格視圖的選定值設置爲會話變量。

它爲我工作...太容易實現。

1

在頁面加載執行此witin

if(!ispostback){ 
    CheckBoxList2.DataSource = ds; //This is the dataset that you fill from your stored procedure; 
    CheckBoxList2.DataTextField = "Tag_Name"; 
    CheckBoxList2.DataValueField = "Tag_Name_Id"; 
    CheckBoxList2.DataBind(); 
} 

,並採取一個參數Tag_Name_Id在SP查詢..

SELECT mst_Tag.Tag_Name,Tag_Name_Id FROM mst_Tag INNER JOIN Post2Tag ON mst_Tag.tagId = Post2Tag.Tag_Id Where [email protected]_Id 

從您的代碼中刪除

foreach (DataRow dr in ds.Rows) 
{ 
    String field1 = dr["Tag_Name"].ToString(); 
    CheckBoxList2.Items.Add(field1); 
    CheckBoxList2.DataBind(); 
} 

希望這會有所幫助......如果是您要求的內容?

+0

Yagnesh @我使用過面板。 在一個面板中有一個網格視圖。 在另一個面板中有一個窗體視圖。 我在表單視圖中使用了這個checkboxlist。 現在選定的索引更改了我的網格視圖控件的事件我想隱藏包含網格視圖的面板並使窗體視圖面板可見。 –