2013-07-09 33 views
0

我正在使用Windows窗體,我想創建一個方法,它將根據datagridview中ComboBox中的項目簡單查看所有數據。如何將我的gridview連接到數據庫?

private void InsertReceipt() 
{ 
     decimal Stub; 

     Stub = decimal.Parse(txtAmount.Text)/2000; 

     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = cn; 
     cmd.CommandType = CommandType.Text; 
     cmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)" + 
        "VALUES (@CustomerID, @Date, @Store, @Amount, @NoStub) "; 
     cmd.Parameters.AddWithValue("@CustomerID", cboName.SelectedValue); 
     cmd.Parameters.AddWithValue("@Date", dtpDate.Value.Date.ToString()); 
     cmd.Parameters.AddWithValue("@Store", txtStore.Text); 
     decimal amount = decimal.Parse(txtAmount.Text); 
     cmd.Parameters.AddWithValue("@Amount", amount); 
     cmd.Parameters.Add("@NoStub", SqlDbType.Decimal).Value = Stub; 

     cmd.ExecuteNonQuery(); 
} 

這是字段,我需要查看所有的數據,這取決於組合框內的項目。

+0

你有什麼錯誤或什麼? –

+0

綁定Gridview,像''select * from tb where cols = combox.value'這樣的查詢引用:http://satindersinght.blogspot.in/2012/08/how-to-addupdate-record-using-gridview.html –

+4

想象一下你是另一個正在閱讀這個問題的人。你能理解這個問題嗎? – rajeemcariazo

回答

0

你提的問題是非常籠統和模糊爲此,很難預答案中的cise。如果你只是想學習如何使用窗體you can find plenty information關於它在線使用datagridview

我發現dotnetpearls一個很好的起點

void FillData() 
{ 
    // 1 
    // Open connection 
    using (SqlCeConnection c = new SqlCeConnection(
    Properties.Settings.Default.DataConnectionString)) 
    { 
    c.Open(); 
    // 2 
    // Create new DataAdapter 
    using (SqlCeDataAdapter a = new SqlCeDataAdapter(
     "SELECT * FROM Animals", c)) 
    { 
     // 3 
     // Use DataAdapter to fill DataTable 
     DataTable t = new DataTable(); 
     a.Fill(t); 
     // 4 
     // Render data onto the screen 
     dataGridView1.DataSource = t; 
    } 
    } 
} 

如果我可以建議更換您通過幾個教程工作,並提出具體的問題,你在哪裏卡住了(錯誤消息等)?

0

使用綁定的GridView這種方法方式與數據從數據庫

protected void BindGridview() 
{ 
using (SqlConnection con = new SqlConnection("Data Source=DatabaseName;Integrated Security=true;Initial Catalog=***"))//Connection string 
{ 
con.Open(); 
SqlCommand cmd = new SqlCommand("Select CustomerID,Date,Store,Amount,NoStub FROM Ticket where ColumnName='"+ YourDrodownId.SlectedValue +"'", con); 
SqlDataReader dr = cmd.ExecuteReader(); 
YourGridview.DataSource = dr; 
YourGridview.DataBind(); 
con.Close(); 
} 
} 

然後設置autogeneratecolumns propertyfalse在我們的GridView控件,並調用此方法在裏面你的頁面加載的或者是你想要的!

這是一個完整的示例代碼!

http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=2

http://forums.asp.net/t/1904884.aspx/1

更新:

在桌面應用程序:

http://www.freedotnetapps.com/sql/database-operations-and-datagridview-bind-in-net-desktop-application/

+0

。 – user2559183

+0

請再看一次我的回答。我給DA打了個鏈接! – 2013-07-09 08:21:01