GridView 是ASP.NET 2.0的新增控制項之一,它的出現代替了原有的DataGrid控制項.如果你使用過ASP.NET 2.0. 在設計GridView控制項時你拖拽了一個Bound Field,那你可能會遇到一個問題.在早期的.NET版本中,如果想要訪問一列,但令它不可見, 你可以將他的Visible屬性設定為false.
但是這在ASP.NET 2.0時無效的.當一個列的可見度設定為false,控制項不會再將資料繫結到該列中,所以你嘗試得到隱藏列的值時,只能得到一個空的字串.
However, this does not work in ASP.Net 2.0. When a column's visibility is set to False, then the Grid does not bind data to the column, and thus when you try to retrieve data from the hidden column, it either blows up or returns an empty string.
對於開發人員來說這個正是可大麻煩,現在提供一個解決方案,希望對你您會有協助
條件
必須擁有Visual Studio 2005 或者 Visual Web Developer Express並對ASP.NET 2.0有一定瞭解
方法一:
在RowCreated事件中書寫如下代碼
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow ||
e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Visible = false; //如果想使第1列不可見,則將它的可見度設為false
}
//可以根據需要設定更多的列
}
因為在RowCreated事件(隱藏)在綁定時候發生,所以這樣就即能將資料繫結到列上,又隱藏了該列.所
以可以訪問到隱藏列的值
方法二:
Public void myTestFunction()
{
string conString="....";//省略
string sqlquery="...";//省略
SqlConnection con = new SqlConnection(conString);
SqlDataAdapter da = new SqlDataAdapter(sqlquery, con);
DataSet ds = new DataSet();
da.Fill(ds);
ds.Tables[0].Columns[0].ColumnMapping = MappingType.Hidden;
GridView1.DataSouce = ds.Tables[0];
GridView1.DataBind() ;
}
方法三:
private void BindGrid()
{
String cmdText = "SELECT KMS_AccountInfo.AccountId, KMS_ServerInfo.ServerId, KMS_ServerInfo.ServerCountryCn, KMS_AccountInfo.StockNum,";
cmdText += " KMS_ServerInfo.ServerName,";
cmdText += " KMS_ServerInfo.GameTypeName,dbo.getmneed(KMS_ServerInfo.ServerId) AS needNum, (dbo.getmkc(KMS_ServerInfo.ServerId)-KMS_AccountInfo.StockNum) AS kcnum,dbo.getmkc(KMS_ServerInfo.ServerId) - dbo.getmneed(KMS_ServerInfo.ServerId) AS CanConvertNum FROM KMS_AccountInfo INNER JOIN";
cmdText += " KMS_ServerInfo ON KMS_AccountInfo.ServerId = KMS_ServerInfo.ServerId inner join kms_gameinfo on KMS_ServerInfo.gameid=kms_gameinfo.gameid Where KMS_ServerInfo.ServerName like '" + txt_ServerName.Text.Trim().ToString() + "%' and KMS_AccountInfo.IsRealStock = 0 and kms_gameinfo.gameid=";
cmdText += Convert.ToInt32(Session["OperatorGame"]);
cmdText += " ORDER BY KMS_ServerInfo.ServerCountryCn DESC, KMS_ServerInfo.ServerName";
SqlDataAdapter myadapter = new SqlDataAdapter(cmdText, myConnection);
DataSet DsOrderList = new DataSet();
myadapter.Fill(DsOrderList);
StockList.DataSource = DsOrderList;
StockList.DataBind();
StockList.Columns[0].Visible = false;
if (myConnection.State.ToString() == "Open") myConnection.Close();
}
在.aspx檔案中設定隱藏列的Visible 屬性為true 綁定後設定其屬性為false即可