![](/img/trans.png)
[英]ArgumentException when adding rows from DataGridView to DataTable
[英]Adding rows to a DataTable from the result of a Query
我正在嘗試做一個簡單的過程,但似乎無法使其正常工作。 請考慮到我是新來的,除了主要的SO職位外,在沒有任何幫助的情況下學習。
我想查詢一個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();
哪里DataTable dtScans = new DataTable();
2)如何從數據庫中正確讀取記錄,然后將它們附加到dtScans
。 我以前使用過SqlDataAdapter.Fill()
方法。 這里合適嗎?
3)一旦弄清楚了,我將使DataTable
成為GridView
的DataTable
DataSource
我從你們那里學到了很多東西,但是在將所有這些縫合在一起的過程中卻遇到了問題。 感謝您的協助。
首先-值得您花時間熟悉ADO.NET框架。 MSDN中有很好的文檔。 這是一個非常基本的ADO任務,但這不是唯一的方法。 您可以從此處開始以獲取有關數據表的信息: http : //msdn.microsoft.com/zh-cn/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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.