c#添加记录到数据绑定DataGridView的文本框

本文关键字:文本 DataGridView 数据绑定 添加 加记录 | 更新日期: 2023-09-27 18:03:51

我是c#数据库的新手。我在SQL Server Management Studio 2012中制作了一个数据库,然后通过选择Visual c#中的DataGridView任务中的数据源将其连接到DataGrid(在Windows窗体中)。我要做的是用新的记录数据填充文本框,然后按下一个按钮,将文本框信息添加到DataGrid中的新行。

c#添加记录到数据绑定DataGridView的文本框

这可能就是您想要的。在sql server数据库中创建一个表,如下所示

CREATE TABLE [dbo].[StudentInfo](
    [StudentId] [numeric](2, 0) IDENTITY(1,1) NOT NULL,
    [SName] [varchar](35) NOT NULL,
    [FName] [varchar](35) NOT NULL,
    [Class] [varchar](35) NOT NULL,
 CONSTRAINT [PK_StudentInfo] PRIMARY KEY CLUSTERED 
(
    [StudentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

现在在您的windows应用程序中使用此代码来更新、删除和保存已创建的表

中的数据
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.DataGrid.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DataGrid_CellClick);
        }
        SqlConnection cn = new SqlConnection("data source=localhost;initial catalog=acc;integrated security=true");
        private void Form1_Load(object sender, EventArgs e)
        {
            TBStudentID.Enabled = false;
            GetData();
        }
        private void GetData()
        {
            SqlDataAdapter da = new SqlDataAdapter("select * from StudentInfo", cn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DataGrid.DataSource = dt;
        }
        private void BtnSave_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("insert into StudentInfo(SName, FName, Class) values('" + TBSName.Text + "','" + TBFName.Text + "','" + TBClass.Text + "')", cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
            GetData();
        }
        // using this CellClick event you will be able to get the selected row values
        // in Respective TextBoxes by clicking any of the datagridview rows
        private void DataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                TBStudentID.Text = DataGrid.Rows[e.RowIndex].Cells[0].Value.ToString();
                TBSName.Text = DataGrid.Rows[e.RowIndex].Cells[1].Value.ToString();
                TBFName.Text = DataGrid.Rows[e.RowIndex].Cells[2].Value.ToString();
                TBClass.Text = DataGrid.Rows[e.RowIndex].Cells[3].Value.ToString();
            }
            catch (Exception)
            {
            }
        }
        private void TextBoxClear()
        {
            TBStudentID.Text = null;
            TBSName.Text = null;
            TBFName.Text = null;
            TBClass.Text = null;
        }
        private void BtnDelete_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("delete from StudentInfo where StudentId = '" + TBStudentID.Text + "'", cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
            GetData();
            TextBoxClear();
        }
        private void BtnUpdate_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("update StudentInfo set SName = '" + TBSName.Text + "', FName = '" + TBFName.Text + "', Class = '" + TBClass.Text + "' where StudentId = '" + TBStudentID.Text + "'", cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
            GetData();
            TextBoxClear();
        }
    }
}

您可以通过使用网格视图的onrowdatabound方法和templatefield

来实现这一点
<asp:GridView ID="gridview" OnRowDataBound="grd_OnRowDataBound">
   <Columns>
      <asp:TemplateField HeaderText="#">
         <ItemTemplate>
            <asp:Label ID="id" runat="server" Text='<%# Bind("data value") %>'></asp:Label>
         </ItemTemplate>
      </asp:TemplateField>
   </Columns>
</asp:GridView>

然后在后端创建方法,如下所示

 protected void grd_OnRowDataBound(Object sender, GridViewRowEventArgs e)
    {
         if (e.Row.RowType == DataControlRowType.DataRow)
         {
             TextBox txtbox = (TextBox)e.Row.FindControl("id");
         }
    }

您可以尝试下面的概念。请看我在no.的笔记。3 .

public Form1()
{
    ds = new DataSet();
    // 1. Create connection.
    conn = new OleDbConnection(@"connection_string.");
    // 2. init SqlDataAdapter with select command and connection
    da = new OleDbDataAdapter("Select * from YouRtable", conn);
    // 3. fill in insert, update, and delete commands 
       (For No. 3 - You can search around the internet on how to construct a SQL Command). You can refer the values that you to insert from the textboxes that you have.)
    OleDbCommandBuilder cmdBldr = new OleDbCommandBuilder(da);
    da.Fill(ds, "YouRtable");
    dataGridView2.DataSource = ds;
    dataGridView2.DataMember = "YouRtable";
}
//Here is your save/update button code.
private void btnSaveGridData_Click(object sender, EventArgs e)
{
    da.Update(ds, "YouRtable");
}