我寧願在我的代碼隱藏中綁定我的服務器控件。我可以更好地調試和測試。我也不需要做其他瘋狂的事情來從代碼隱藏中獲得我的綁定數據......它已經在那裏了。這是一個例子。
假設以下存儲過程在SQL:
CREATE PROCEDURE selEmployees
@DeptId int,
@SearchString varchar(100)
AS
BEGIN
SELECT TOP 1000 * FROM Employees
WHERE DeptId = @DeptId AND CONTAINS(*, SearchString);
END
我可以在存儲過程相匹配的方法在我的實體類或頁面代碼隱藏,像這樣:
public static DataSet selEmployees(int DeptId, string SearchString)
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(clsData.getConnString());
SqlCommand cmd = new SqlCommand("selEmployees", con); // stored proc name
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter _DeptId = cmd.Parameters.Add("@DeptId", SqlDbType.Int); //stored proc parameter name and datatype
_DeptId.Value = DeptId; //assign method parameter value to sql parameter
SqlParameter _SearchString = cmd.Parameters.Add("@SearchString", SqlDbType.Int); //stored proc parameter name and datatype
_SearchString.Value = SearchString; //assign method parameter value to sql parameter
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
adapt.SelectCommand = cmd;
con.Open();
try
{
adapt.Fill(ds);
}
catch (Exception ex)
{
string msg = ex.ToString();
}
finally
{
con.Close();
con.Dispose();
}
return ds;
}
然後,我可以像這樣綁定我的數據到我的服務器控件在page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = Employees.selEmployees(MyDeptId, MySearchString);
GridView1.DataBind();
}
}
如果您嘗試此操作,請確保rem在標記中填入GridView的DataSourceId參數。 DataSource和DataSourceId在一起玩不起來。
注意:實際上有一百萬個更好的方法來做到這一點。這篇文章的目的是爲了說明在標記中使用SqlDataSource的一個簡單方法。藉此一步futher
的方法之一是生成的數據集分配給像一個頁面屬性可重複使用的變量:
public partial class ViewEmployees : System.Web.UI.Page
{
public DataSet DataSetEmployees { get; set; } //re-usable property gets set at page_load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//save the dataset to a re-usable property
DataSetEmployees = Employees.selEmployees(MyDeptId, MySearchString);
//bind using the property
GridView1.DataSource = DataSetEmployees;
GridView1.DataBind();
}
}
}
有了這麼簡單升級,則必須使用和重新的能力在整個頁面中使用DataSet,而不必重新查詢數據庫。
我不再使用SqlDataSource,但是當我這樣做時,我需要在我的代碼隱藏中獲得DataTable,這正是我如何做到的。 – 2010-02-12 04:45:04
@Byron Sommardahl:謝謝!你現在用什麼? – abatishchev 2010-02-12 07:06:18
好吧,爲了更好地控制和正確測試,我將我的服務器控件綁定到了代碼隱藏的數據集。我會用一個例子發表一個答案。 – 2010-02-12 21:48:02