繁体   English   中英

如何将GridView连接到数据库?

[英]How to connect my gridview to database?

我正在使用Windows窗体,并且我想创建一个方法,该方法将仅根据datagridview中 ComboBox内部的项目查看所有数据。

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();
}

这是字段,我需要根据ComboBox中的项目查看所有数据。

使用这种方法将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();
}
}

然后在我们的Gridview控件中将autogeneratecolumns property设置为false ,然后在您的页面加载过程中调用该方法,或者在您想要的时候调用此方法!

这是带有代码的完整示例!

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/

您的问题非常笼统,含糊其词,答案很难准确。 如果您只是想学习如何在Windows窗体中使用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;
    }
    }
}

如果我可以建议您通过一些教程来学习,并询问您遇到的具体问题(出现错误消息等)?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM