向数据表中添加列并添加数据

本文关键字:添加 数据 数据表 | 更新日期: 2023-09-27 17:53:42

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

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

                }
            }
        }

向数据表中添加列并添加数据

dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];
dt.Columns.Add("ColumnName", typeof(DataType));
if (dr["ProductCode"].ToString().Equals(productCode))
{
    dr["ColumnName"] = value;    
}

进一步我将扩展代码以避免NullReferenceException

 if (!String.IsNullOrEmpty(dr["ProductCode"]) && dr["ProductCode"].ToString().Equals(productCode))
 {
        dr["ColumnName"] = value;    
 }
http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx