與 「最老」 的解決方案去 - ADO.NET - 你可以寫這樣的事情:
// define a class to hold the data returned from the stored procedure
public class SPReturnData
{
public string EmployeeUsername { get; set; }
public string ApprovedBy { get; set; }
public string BranchName { get; set; }
}
// define a method to call the stored proc and return the data
public SPReturnData LoadData(string connectionString, string employeeName)
{
// initialize the structure to be returned
SPReturnData result = new SPReturnData();
// setup ADO.NET connection and command
using(SqlConnection conn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand("dbo.SP_ShowUse", conn))
{
// it's a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// set up the command's parameters
cmd.Parameters.Add("@EmployeeName", SqlDbType.VarChar, 50).Value = employeeName;
// open connection, execute command, close connection
conn.Open();
// execute reader
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.Read())
{
// first column -> employee user name
result.EmployeeUserName = rdr.GetString(0);
// second column -> approved by name
result.ApprovedBy = rdr.GetString(1);
// third column -> Branch name
result.BranchName = rdr.GetString(2);
}
rdr.Close();
}
conn.Close();
}
return result;
}
從你的代碼 - 使用這樣的:
// pass in the connection string (e.g. get it from config or something)
// and the employee name - get back a "SPReturnData" object with the data items
SPReturnData data = LoadData("server=.;database=.....;", "Fred Flintstone");
// set your textboxes to the values returned
txtEmployeeName.Text = data.EmployeeName;
txtApprovedBy.Text = data.ApprovedBy;
txtBranchName.Text = data.BranchName;
@raghu marcs answer也不錯... – SoftwareNerd 2012-02-21 05:37:17