【问题标题】:How to Insert Data in Database through DataGridView in Windows Form Application如何在 Windows 窗体应用程序中通过 DataGridView 将数据插入数据库
【发布时间】:2013-08-23 20:02:46
【问题描述】:

我正在用 c# 制作一个 Windows 窗体应用程序,其中有一个绑定到 SQL Server 数据库的网格视图控件。所有人都希望,让用户按 CTRL + N 并且新行显示为网格视图的第一行,并且在该行中输入数据时,应通过按 Enter 将数据插入数据库并进行所有验证检查。为此,我使用文本框,但不知道如何使用网格视图。

 private void btnsave_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand cmd = DataConnection.GetConnection().CreateCommand();
            cmd.CommandText = "insert into CustomerMaster(CustId,Name,City,State,Pin,ContactInfo) values(@custid,@name,@city,@state,@pin,@contactinfo)";
            cmd.Parameters.Add(new SqlParameter("@custid", txtcustid.Text));
            cmd.Parameters.Add(new SqlParameter("@name", txtname.Text));
            cmd.Parameters.Add(new SqlParameter("@city", txtcity.Text));
            cmd.Parameters.Add(new SqlParameter("@state", txtstate.Text));
            cmd.Parameters.Add(new SqlParameter("@pin", txtpin.Text));
            cmd.Parameters.Add(new SqlParameter("@contactinfo", txtcontactinfo.Text));

            bool ans = cmd.ExecuteNonQuery() > 0;
            if (ans)
            {
                MessageBox.Show("Insertion Happens Successfully");

            }
            else
            {
                MessageBox.Show("Insertion doesnot Happens");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

【问题讨论】:

  • 你试过什么?发布您的代码
  • 对于插入数据,我使用一个选项卡控件,其中一个选项卡中有网格视图来显示数据,而另一个选项卡中有标签及其关联的文本框。

标签: c# datagridview


【解决方案1】:

您有多个问题。我会回答“如何添加空行”一。

为此,在填充数据集并将其绑定到 Grid 之前,您应该在该数据集的顶部添加一个空行。

' insert a blank row at the top
  Dim dr As DataRow = MyGrid.Tables(0).NewRow()
  dr("MyFiled") = "0"
  MyGrid.Tables(0).Rows.InsertAt(dr, 0)

互联网上有很多文章展示了如何保存数据。如果您对这些有疑问,请在此处编写您的特定代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多