不使用数据行循环进行数据表更新

时间:2013-08-13 19:26:49

标签: c# asp.net linq datatable

是否可以执行以下操作:

我有以下数据表

=================================
ID      ||   Width  ||  Value  ||
=================================
size-1  ||   50     ||         ||
name-1  ||   100    ||         ||
zip-1   ||   50     ||         ||
size-2  ||   50     ||         ||
name-2  ||   100    ||         ||
zip-2   ||   50     ||         ||
=================================

我希望能够循环遍历数据表并使用textcontrolbox.text值更新value列

Session[sectionName] = test;
DataTable dt = (DataTable)Session[sectionName];

        var strIDS = from p in dt.AsEnumerable()
                     select new
                     {
                         ID = p.Field<string>("ID")
                     };

        foreach (var strID in strIDS)
        {
            TextBox tempBox = DynamicControlsHolder1.FindControl(strID.ID) as TextBox;
            string val = tempBox.Text;

            // This is where i want to be able to update the value column, but i can't figure out how to
            // Can someone please help

        }

2 个答案:

答案 0 :(得分:3)

您的整个代码可以替换为:

foreach (DataRow Row in dt.Rows)
    Row["Value"] = (DynamicControlsHolder1.FindControl(Row["ID"]) as TextBox).Text;

答案 1 :(得分:3)

int i = 0;
foreach (var strID in strIDS)
    {
        TextBox tempBox = DynamicControlsHolder1.FindControl(strID.ID) as TextBox;
        dt.Rows[i++]["Value"] = tempBox.Text;
    }

我认为您应该尝试在LINQ中更新,如下所示:

var totalRows = dt.AsEnumerable()                  
                  .Select(p=>                     
                  {
                     p["Value"] = (DynamicControlsHolder1.FindControl(p.Field<string>("ID")) as TextBox) ?? "";
                     return p;
                  }).Count();

要更新特定行,您可以尝试:

var row = dt.AsEnumerable()
            .Where(p=>p.Field<string>("ID") == "ID you want").FirstOrDefault();
if(row != null) row["Value"] = (DynamicControlsHolder1.FindControl(row["ID"].ToString()) as TextBox).Text;