2010-09-24 34 views
0

我並不真正習慣於C#sharp,但之前使用過VB.NET。C#:幫助返回數據集並將值分配給控件

我需要設置來自查詢數據的文本字段,下拉列表等的值。要輸入數據,我一直在使用帶有saveComputer()方法的類Computer,該方法從用戶控件獲取值。現在我想要一個使用來自url &的ID的編輯頁面,它使用Computer類中的getComputer(id)並返回要設置爲用戶控件的值。我不確定使用這種方法來設置控制值。

Edit.aspx.cs

protected void btnSave_Click(object sender, EventArgs e) 
    { 
     int id = 3; //will be replaced to GET value 
     Computer comp = new Computer(); 
     //comp.updateComputer(ref id); 

    } 

我的電腦類

public getComputer(ref int id) 
    { 
     DataSet data = new DataSet(); 
     using (SqlConnection conn = new SqlConnection(
       "Server=JURA;Database=ReadyForSeven;User id=;Password=")) 
     { 
      String sql = "SELECT * FROM computers WHERE [email protected]"; 

      //replace contatenation of variable with parameter name 


      SqlCommand cmd = new SqlCommand(); 
      cmd.Connection = conn; 
      cmd.CommandText = sql.ToString(); 
      cmd.CommandType = CommandType.Text; 

      //Define SqlParameter object and assign value to the parameter 

      cmd.Parameters.Add("@id", SqlDbType.Int); 
      cmd.Parameters["@id"].Value = id; 

      try 
      { 
       using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
       { 
        da.Fill(data); 
        // return data here 
       } 
      } 
      catch (SqlException ex) 
      { 
       //send user to error page and log message 

      } 
     } 
    } 

那麼我現在想使用計算機的getcomputer方法來設置的值來實現Edit.aspx上的控件

任何人都可以幫我嗎?

+0

當我們對你的數據庫結構一無所知時,很難提供幫助,沒有關於它的哪些部分是有趣的,也沒有關於你想要賦值的控件。 – 2010-09-24 10:39:56

回答

1

你需要修改getComputer方法返回一個DataSet,如:

public DataSet getComputer(int id) { 

一旦這樣做了,我們可以把它與類似填充在頁面加載表單控件:

protected void Page_Load(object sender, EventArgs e) { 
    if (!IsPostBack) { 
     int id = 3; // get from querystring 
     DataSet ds = getComputer(id); 
     DataRow dr = ds.Tables[0].Rows[0]; // get the first row returned 

     // populate form controls 
     txtFirstName.Text = dr["FirstName"].ToString(); 
     ddlState.SelectedValue = dr["State"].ToString(); 
    } 
} 

以下是getComputer的更新版本,它會始終返回一個值並且稍微更緊密:

public DataSet getComputer(int id) // you don't need to pass int by ref unless you're planning on changing it inside this method 
{ 
    DataSet data = new DataSet(); 
    using (SqlConnection conn = new SqlConnection("Server=JURA;Database=ReadyForSeven;User id=;Password=")) { 
     using (SqlCommand cmd = new SqlCommand("SELECT * FROM computers WHERE id = @id", conn)) { 
      cmd.Parameters.AddWithValue("id", id); 
      using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { 
       da.Fill(data); 
       return data; 
      } 
     } 
    } 
} 

我不得不刪除try/catch博客以確保該方法總是返回一個值。如果你確實需要try/catch塊,你需要在方法末尾返回一個空的DataSet以正確編譯。

+0

謝謝!但我得到一個不是所有的代碼路徑現在從getComputer方法返回一個值錯誤 – iamjonesy 2010-09-24 11:06:18

+0

Do'h,我添加了getComputer的更新版本,總是返回一個值。 – 2010-09-24 11:38:52

相關問題