从datagrid视图保存记录 [英] save records from datagrid view

查看:76
本文介绍了从datagrid视图保存记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,该表单具有一个带有两列clmCategoary和clmActivity
的datagridview 当我单击保存按钮时,应将所有gridview中的插入到数据库中.
但显示错误消息无效的列名".请问我该怎么办

i have a form which has a datagridview with two columns clmCategoary and clmActivity
when i click the save button it should insert the in all the gridview into the db.
but it gives the error message "invalid column name". pls what should i do

private void btnSave_Click(object sender, EventArgs e)
        {
            string StrQuery;
            try
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]))
                {
                    conn.ConnectionString = "Data Source=MICKY-PC;Initial Catalog=MUCGPROJECT;User ID=sa;Password=mike";
                     using (SqlCommand comm = new SqlCommand())
                       {
                            comm.Connection = conn;
                            conn.Open();
                             for(int i=0; i< dataGridView1.Rows.Count;i++)
                            {
                                StrQuery = @"INSERT INTO CategorynA VALUES (" + dataGridView1.Rows[i].Cells["clmCategory"].Value + ", " + dataGridView1.Rows[i].Cells["clmActivity"].Value + ");";
                                comm.CommandText = StrQuery;
                                comm.ExecuteNonQuery();
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

推荐答案

我相信您在查询中缺少单引号
I believe you are missing single quotes in your query
StrQuery = @"INSERT INTO CategorynA VALUES ('" + dataGridView1.Rows[i].Cells["clmCategory"].Value + "', '" + dataGridView1.Rows[i].Cells["clmActivity"].Value + "');";


,但显示错误消息无效的列名"
这仅表示形成的插入查询具有无效的列名.

只需在执行查询之前设置一个断点,使用DEBUGGER并查看形成的查询:
but it gives the error message "invalid column name"
It simply means that the insert query formed has an invalid column name.

Simply put a break point before query execution, use DEBUGGER and see what is the formed query:
StrQuery = @"INSERT INTO CategorynA VALUES (" + dataGridView1.Rows[i].Cells["clmCategory"].Value + ", " + dataGridView1.Rows[i].Cells["clmActivity"].Value + ");";


通过直接在SQL Server中运行以验证它是否正常来进行验证.检查表中是否存在列名称集.


Verify it by directly running in SQL server to see if it is fine. Check the column name set is present in table.


您好,

我认为您忘记指定字段名称:

例如:
Hi,

In my opinion you forgot to specify you field names:

example:
StrQuery = @"INSERT INTO [dbo].[CategorynA](Category, Activity) VALUES ('" + dataGridView1.Rows[i].Cells["clmCategory"].Value + "', '" + dataGridView1.Rows[i].Cells["clmActivity"].Value + "');";



请帮忙投票...



Please do not forget to vote if could help...


这篇关于从datagrid视图保存记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆