2010-10-23 141 views
0

如何以編程方式在gridview中添加複選框字段,我的代碼有什麼問題?如何在GridView中添加CheckBox字段?

try 
{ 
    string [email protected]"Data Source=A-63A9D4D7E7834\SECOND;"; 
    string [email protected]"Initial Catalog=replicate;"; 
    string [email protected]"User ID=sa;"; 
    string [email protected]"Password=two"; 
    string full_con=Data_source+Initial_Catalog+User+Password; 
    SqlConnection connection = new SqlConnection(full_con); 
    connection.Open(); 
    SqlCommand numberofrecords = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection); 
    DataSet ds2 = new DataSet(); 
    SqlDataAdapter testadaptor = new SqlDataAdapter(); 
    testadaptor.SelectCommand = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection); 
    testadaptor.Fill(ds2); 
    grid1.DataSource = ds2; 
    CheckBoxField c = new CheckBoxField(); 
    grid1.Columns.Add(c); 
    grid1.DataBind(); 
    numberofrecords.Dispose(); 
    connection.Close(); 
    connection.Dispose(); 
} 
catch (Exception a) 
{ 
    Response.Write("Please check "); 
    Response.Write(a.Message.ToString()); 
    Response.Write(a.Source.ToString()); 
}//catch 

回答

1

CheckBoxField可能需要DataField屬性的值。這應該與查詢中的列名或別名相匹配。 (雖然我不認爲複選框會與數字結果一起工作)。

編輯:沒有意識到你正在嘗試做什麼。模板字段和常規復選框應該讓你更接近你想要的東西。像這樣?

例如

const int ColumnSelect = 0; 

protected void Page_Load(object sender, EventArgs e) 
{  
    //Get real data here. 
    DataTable dt = new DataTable(); 
    dt.Columns.Add("count");     
    dt.Rows.Add(dt.NewRow()); 
    dt.Rows[0][0] = "5"; 

    GridView1.Columns.Add(new TemplateField());   
    BoundField b = new BoundField(); 
    GridView1.Columns.Add(b); 
    b.DataField = "count"; 
    GridView1.DataSource = dt; 
    GridView1.DataBind(); 
} 


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType != DataControlRowType.Header) 
    {    
     e.Row.Cells[ColumnSelect].Controls.Add(new CheckBox()); 
    } 
} 

編輯#2:爲所獲得的價值,你一定可以做到這一點。你在尋找一個Javascript還是服務器端解決方案?這裏有一個簡單的例子,服務器端,如果你有一個按鈕,點擊:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    foreach(GridViewRow row in GridView1.Rows) 
    { 
     //Could also use (CheckBox)row.Cells[ColumnSelect].FindControl if you give the checkboxes IDs when generating them. 
     CheckBox cb = (CheckBox)row.Cells[ColumnSelect].Controls[0]; 

     if (cb.Checked) 
     { 
      //Do something here. 
     } 
    } 
} 
+0

nope,這不起作用,它不應該與任何東西綁定 – user287745 2010-10-24 04:37:21

+1

好吧,我現在看到。修改我的答案。 – Bitwise 2010-10-24 22:30:21

+0

這個複選框會在選中時幫助我檢測它所屬的行嗎? – user287745 2010-10-25 19:28:34

0

我不得不指定複選框對象,這樣

 System.Web.UI.WebControls.CheckBox 

此外,我不得不把它添加到GridView aspx頁面

 OnRowDataBound="GridView1_RowDataBound" 
相關問題