繁体   English   中英

C#使用文本框将记录添加到DataBound DataGridView

[英]C# Add Record to DataBound DataGridView with textboxes

我是整个C#数据库的新手。 我在SQL Server Management Studio 2012中创建了一个数据库,然后通过从Visual C#的DataGridView Tasks中选择DataSource将其连接到DataGrid(在Windows窗体中)。 我要做的是用新的记录数据填充texbox,然后按一个按钮,将文本框信息添加到DataGrid的新行中。 任何帮助将不胜感激。

您可以通过将网格视图的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");
         }
    }

您可以尝试以下概念。 请参阅我的注释。 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");
}

这可能就是您想要的。 在您的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();
        }
    }
}

暂无
暂无

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

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