2016-12-06 70 views
0

我試圖做一個簡單的過程,但似乎無法使其正常工作。請考慮到我是這方面的新手,並且除了大多數SO職位外沒有任何幫助學習。從查詢結果中將行添加到DataTable中

我想查詢一個SQL Server表,然後將檢索到的記錄追加到DataTable。以下是我迄今爲止:

ASPX:

<form id="form1" runat="server"> 
    <div> 
     <asp:TextBox ID="txtScan" runat="server"></asp:TextBox><br /> 

     <asp:Button ID="btnSearch" runat="server" Text="SEARCH" OnClick="btnSearch_Click" /> 
    </div> 

CS:

using System; 
using System.Data; 
using System.Data.SqlClient; 
using System.Configuration; 

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 

    protected void btnSearch_Click(object sender, EventArgs e) 
    { 
     AddItem(); 
    } 

    protected void AddItem() 
    { 
     using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["2008DB"].ConnectionString)) 
     { 
      SqlCommand cmd = new SqlCommand(); 
      SqlDataAdapter da = new SqlDataAdapter(cmd); 

      cmd.Connection = conn; 
      cmd.CommandText = "select * from items where ID = @lookup"; 
      cmd.Parameters.Add("@lookup", SqlDbType.NVarChar).Value = btnSearch.Text; 
      da.Fill(dtScans); //I shouldn't be filling this I don't think? 

     } 
    } 
} 

我弄混自己是以下幾點:

1)如果把DataTable dtScans = new DataTable();

2)如何從數據庫中正確讀取記錄,然後將它們追加到dtScans。我以前使用過​​的方法。這在這裏適合嗎?

3)一旦這樣figuered出來,我就能做出DataTableDataSourceGridView

我已經學到了很多東西你們,但我有這一個縫合所有的一起問題。感謝您的幫助。

回答

1

首先 - 值得您花時間熟悉ADO.NET框架。 MSDN中有很好的文檔。這是一個非常基本的ADO任務,但它不是唯一的方法。你可以從這裏開始獲取有關數據表的信息:http://msdn.microsoft.com/en-us/library/t31h6yhs%28v=vs.110%29.aspx

這就是說,你很近!你需要創建一個新的DataTable實例,然後你可以填充它,就像你說的。如果您只打算使用一次,它可以在您的AddItem()方法中正確使用。填好後,您可以將其綁定到您的GridView

protected void AddItem() 
{ 
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["2008DB"].ConnectionString)) 
    { 
     SqlCommand cmd = new SqlCommand(); 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 

     cmd.Connection = conn; 
     cmd.CommandText = "select * from items where ID = @lookup"; 
     cmd.Parameters.Add("@lookup", SqlDbType.NVarChar).Value = txtScan.Text; //You'll also want to fix this line to use the TextBox instead of the Button 

     DataTable dtScans = new DataTable(); //Create the new DataTable so you have something to fill 
     da.Fill(dtScans); 
     GridView1.DataSource = dtScans; //Set the DataTable to be the sourse for a GridView 
    } 
} 
+0

謝謝好的我有這麼多 - 如果我想繼續爲新項目輸入並將它們附加到dtScans?這是我真正卡住的地方。我被卡住重新使用DataTable添加其他項目。感謝您的幫助@squillman – Mobilemike