简体   繁体   中英

How to update a particular column in datatable?

I have a datatable something like this.

ColA      ColB       ColC
100       text10     text25
100       text15     
100                  text26
100                  text25
100       text14     text22

I want to change the values in ColB and ColC by adding a leading and trailing character only for the non-empty values in the datatable.

ColA      ColB       ColC
100       -text10-   -text25-
100       -text15-     
100                  -text26-
100                  -text25-
100       -text14-   -text22-

EDIT:I was able to do it by looping thru the datarows and updating it. But i am searching for a easier and simpler options. Is there a way to achieve this using LINQ?

LINQ to achieve it be like:

Assuming your DbContext name is "testEntities" in EF and table name is multicols . You can try:

using (var db = new testEntities())
{
    (from m in db.multicols
          where m.ColB != null || m.ColC != null //Dont pull if both columns are null
          select m).ToList().ForEach( m =>
          {
              m.ColB = String.IsNullOrEmpty(m.ColB) ? m.ColB : $"-{m.ColB}-";
              m.ColC = String.IsNullOrEmpty(m.ColC) ? m.ColC : $"-{m.ColC}-";
           });

    db.SaveChanges();
}
Private dt As New DataTable

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    dt.Columns.Add("ColumnA", GetType(Integer))
    dt.Columns.Add("ColumnB", GetType(String))
    dt.Columns.Add("ColumnC", GetType(String))
    dt.Rows.Add(100, "text10", "text25")
    dt.Rows.Add(100, "text15")
    dt.Rows.Add(100, "", "text26")
    dt.Rows.Add(100, "", "text25")
    dt.Rows.Add(100, "text14", "text22")
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    For Each row As DataRow In dt.Rows
        Dim colB As String = row(1).ToString
        Dim colC As String = row(2).ToString
        If Not String.IsNullOrEmpty(colB) Then
            row(1) = $"-{colB}-"
        End If
        If Not String.IsNullOrEmpty(colC) Then
            row(2) = $"-{colC}-"
        End If
    Next
    DataGridView1.DataSource = dt
End Sub

I tested ColumnB and ColumnC separately and update the data in the DataGable with an interpolated string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM