C# 向数据表添加列并添加数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14336257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:28:23  来源:igfitidea点击:

Adding a column to a datatable and adding data

c#sql-serverdatatabledataset

提问by Arianule

How can I add a column to a datatable and add data to each row based on a condition. This is what I am trying to do

如何将一列添加到数据表并根据条件将数据添加到每一行。这就是我想要做的

conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;
                                Data Source =" + Server.MapPath("App_Data\LR Product Database 2000.mdb"));
        conn.Open();

        Dictionary<string, string> items = new Dictionary<string, string>();
        OleDbCommand cmd = conn.CreateCommand();
        cmd.CommandText = "SELECT CODE, TITLE FROM tblProducts";

        OleDbDataReader dbread = cmd.ExecuteReader();

        while (dbread.Read())
        {
            productCode = (string)dbread["ProductCode"];
            productTitle = items[productCode];
            items.Add(productCode, productTitle);
        }

        sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["LRVWebsite"].ToString());
        sqlCon.Open();
        dsSql = new DataSet();
        SqlDataAdapter dba = new SqlDataAdapter(@"SELECT C.CustomerFirstName,C.CustomerLastName, C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
        dba.Fill(dsSql,"Products");
        DataTable dt = dsSql.Tables["Products"];

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < items.Count; i++)
            {
                if (dr["ProductCode"].ToString().Equals(productCode))
                {
                    //here I want to add a new column and add data (productTitle) to the column


                }
            }

        }

采纳答案by Daniel W.

dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];

dt.Columns.Add("ColumnName", typeof(DataType));

if (dr["ProductCode"].ToString().Equals(productCode))
{
    dr["ColumnName"] = value;    
}

Further i would extend the code to avoid NullReferenceException

此外,我会扩展代码以避免 NullReferenceException

 if (!String.IsNullOrEmpty(dr["ProductCode"]) && dr["ProductCode"].ToString().Equals(productCode))
 {
        dr["ColumnName"] = value;    
 }

http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx

http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx