将变量放入sql命令 [英] Putting variable into sql command

查看:96
本文介绍了将变量放入sql命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环,它从datagrid收集行id,然后我想将所有那些行id插入到我的sql语句中,用数据库中最新的数据重新加载datagrid。这可能吗? sql语句似乎只有
拉1行。

I have a for loop which is gathering the row id's from the datagrid and then I want to insert all those row id's into my sql statement to reload the datagrid with the most current data from the database. Is this possible? The sql statement seems to be only pulling 1 row.

void datagrid_refresh()
        {
            foreach (DataRowView dr in dgTracking.ItemsSource)
            {
                using (SqlConnection sqlcon = new SqlConnection(sqlDb))
                {
                    sqlcon.Open();
                    string refreshQuery = "SELECT * FROM tblTracking WHERE Id=@Id";
                    SqlDataAdapter refreshDa = new SqlDataAdapter(refreshQuery, sqlcon);
                    refreshDa.SelectCommand.Parameters.AddWithValue("@Id", dr[0]);
                    DataTable dtbl = new DataTable();
                    refreshDa.Fill(dtbl);
                    if (dtbl.Rows.Count > 0)
                    {
                        dgTracking.AutoGenerateColumns = false;
                        dgTracking.ItemsSource = dtbl.DefaultView;
                    }
                    sqlcon.Close();
                }
            }
        }

推荐答案

在你的循环中,你继续用当前的@ Id替换ItemsSource。 如果您要在循环中的每次迭代中使用DataTable作为ItemsSource,则需要添加ItemsSource。 我从不使用DataTable,我使用集合
的对象。 这样做就可以在循环之前清除集合,并在每次获得刷新的数据项时将项添加到集合中。
In your loop you keep replacing the ItemsSource with the current @Id.  If you are going to use a DataTable as your ItemsSource with each iteration in the loop you would need to add the the ItemsSource.  I never use DataTable, I use collections of objects.  Doing it that way you would clear the collection before the loop and add an item to the collection each time you get a refreshed data item.


这篇关于将变量放入sql命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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