简体   繁体   English

将不均匀数据从Datagridview插入数据库C#的问题

[英]Issues with Inserting uneven data from datagridview into database c#

Hi i have this codes that insert data from datagridview to database 嗨,我有这段代码可以将数据从datagridview插入数据库

for (int i = 0; i < ADODB.Rows.Count - 1; i++)
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO Employee VALUES(@Team, @SIC, @EID,@EmployeeName,@Username,@Password,@Designation,@Department,@Email,@HireDate,@TakenAL,@Status)", con);

            cmd.Parameters.AddWithValue("@Team", ADODB.Rows[i].Cells[0].Value);
            cmd.Parameters.AddWithValue("@SIC", ADODB.Rows[i].Cells[1].Value);
            cmd.Parameters.AddWithValue("@EID", ADODB.Rows[i].Cells[2].Value);
            cmd.Parameters.AddWithValue("@EmployeeName", ADODB.Rows[i].Cells[3].Value);
            cmd.Parameters.AddWithValue("@Username", ADODB.Rows[i].Cells[4].Value);
            cmd.Parameters.AddWithValue("@Password", ADODB.Rows[i].Cells[5].Value);
            cmd.Parameters.AddWithValue("@Designation", ADODB.Rows[i].Cells[6].Value);
            cmd.Parameters.AddWithValue("@Department", ADODB.Rows[i].Cells[7].Value);
            cmd.Parameters.AddWithValue("@Email", ADODB.Rows[i].Cells[8].Value);
            cmd.Parameters.AddWithValue("@HireDate", ADODB.Rows[i].Cells[9].Value);
            cmd.Parameters.AddWithValue("@TakenAL", ADODB.Rows[i].Cells[10].Value);
            cmd.Parameters.AddWithValue("@Status", ADODB.Rows[i].Cells[11].Value);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

I would like to ask what if i have 12 columns in my datagridview but my database has 13 columns. 我想问一下我的datagridview中是否有12列,但是我的数据库有13列。 It would prompt an error due to the the difference in things that are added. 由于所添加内容的差异,将提示错误。 How do i solve this problem? 我该如何解决这个问题? Thanks in advance 提前致谢

Use name reference for the columns, ie 对列使用名称引用,即

        cmd.Parameters.AddWithValue("@Team", ADODB.Rows[i].Cells["Team"].Value);
        cmd.Parameters.AddWithValue("@SIC", ADODB.Rows[i].Cells["SIC"].Value);
        cmd.Parameters.AddWithValue("@EID", ADODB.Rows[i].Cells["EID"].Value);

The columns will receive their name from the database column, when you load data from database. 当您从数据库加载数据时,这些列将从数据库列中接收其名称。 Other way is to set and name the columns via GUI in VS, or via code, ie: 另一种方法是通过VS中的GUI或通过代码来设置和命名列,即:

DataGridView1.Column[2].Name = "EID"

If you design your column scheme of datagridview in GUI or code first, make sure you use 如果先在GUI或代码中设计datagridview的列方案,请确保使用

DataGridView1.AutoGenerateColumns = False

and that your use that name reference when loading data, using DataPropertyName: 并且使用DataPropertyName在加载数据时使用该名称引用:

DataGridView1.Column[2].DataPropertyName = "EID" 

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

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