GridView 是 ASP.NET 2.0 中應用最廣泛的資料控制項之一,幾乎所有數據操作都离不开它。正如我們平常所用,它可以編輯、刪除、選擇等等。但如果客戶希望能「點擊整列」就觸發超連結或進入列編輯狀態,該如何實作?本文介紹一種做法,讓你能透過點擊列的任意位置來引發所需的事件。
首先,為 GridView 填入數據:
private void BindData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT * FROM Users", myConnection);
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
接著,我們在 GridView 的 RowDataBound 事件中,為 GridViewRow 加上點擊屬性:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string alertBox = "alert('";
if (e.Row.RowType == DataControlRowType.DataRow)
{
alertBox += e.Row.RowIndex;
alertBox += "')";
e.Row.Attributes.Add("onclick", alertBox);
}
}
就這麼簡單,希望對你有所幫助!