简体   繁体   中英

How I can get one Row or Column From DataTable

I am connected to my SQL Server database and this is my code:

public string Get()
{
    string Sql3 = "(SELECT TOP 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song, Speaker_Volume, Speaker_Availability, Speaker_Mute, Date_Time, Speaker_Status, ROW_NUMBER() OVER (ORDER BY Date_Time DESC) AS RowNumber FROM Raspi_speaker)T";

    string Sql2 = "Speaker_Volume, Speaker_Status, Speaker_Availability, Speaker_Mute, Date_Time, RowNumber FROM";

    string Sql = "SELECT TOP 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song, " + Sql2 + Sql3;

    SqlDataAdapter adap = new SqlDataAdapter(Sql, conn);
       
    DataTable dataTable = new DataTable();
        
    dynamic dynObject = new ExpandoObject();
    adap.Fill(dataTable);

    if (dataTable.Rows.Count > 0)
    {
        return JsonConvert.SerializeObject(dataTable);
    }

    return "No Data Found";
}

This code displays ALL the data in the table, but I want to get only one column or one row from the DataTable variable and display only one column or one row - how can I do that?

To display an indexed row (index):

DataRow dr = dataTable.Rows[index];
foreach(DataColumn dc in dataTable.Columns)
{
    Console.WriteLine(dr[dc.ColumnName].ToString()); // makes a list of values of what you need
}

To display a column name (columnName):

foreach(DataRow dr in dataTable.Rows)
{
    Console.WriteLine(dr[columnName].ToString()); // makes a list of values of what you need
}

To return the intersection of an indexed row and column name:

DataRow dr = dataTable.Rows[index];
Console.WriteLine(dr[columnName].ToString());// is the only value you need

Seems to me here, that since the return is JSON, then the goal is to send (return) a single data.table row as JSON.

Ok, the serializer from Newtonsoft can return one row, but, it WILL have additonal tags (attributes) surrounding the row.

So, say this code:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim strSQL =
        "SELECT ID,FirstName, LastName, HotelName,City FROM tblHotels WHERE ID in (19,23)"

    Using conn As New SqlConnection(My.Settings.TEST4)
        Using cmdSQL As New SqlCommand(strSQL, conn)

            conn.Open()
            Dim rstData As New DataTable
            rstData.Load(cmdSQL.ExecuteReader)

            Dim strJASON As String

            strJASON = JsonConvert.SerializeObject(rstData)

            TextBox1.Text = strJASON & vbCrLf & "-------" & vbCrLf

            TextBox1.Text &= JsonConvert.SerializeObject(rstData.Rows(0))


        End Using
    End Using

End Sub

We, return two rows, and you do get a nice JSON arrary as a result.

eg this:

在此处输入图像描述

So if you serialize ONE row, then you get the extra two tags of "row state", and "row error". But, it NOT an array (no [] around the json string).

So, if you can live with the row state/error being added, then that's probably the best solution.

However, if you don't want the row tags, then probably better to limit the rows in the datatable to ONE row, and then send that, you will client side have to use index [0] since as you can see, the results are cleaner then serializing a single row, but it is thus an array.

So, with this:

 "SELECT ID,FirstName, LastName, HotelName,City FROM tblHotels WHERE ID in (19)"

You now get this:

在此处输入图像描述

So, you can use "row", but it will add the extra attributes to the json string (row status + row error. If you don't care, then serialize a row data type.

If you do care, don't want the extra attributes? Then best to serialize the whole data.table, which thus means you want to limit the rows in the datatable to one row BEFORE you convert to json.

Now, at the end of the day? Quite obvious the goal here is to send that one data row as JSON, and I don't know of a clean way to send a data row as JUST one row of JSON data, without the extra row attributes (rowstate, rowerror, table).

So, if you don't care about having the 3 extra attributes? Then serialize the row as per above. If you do care, then better to pull ONLY one row into a datatable, and send that to the serializer. You get a clean JSON, but inside of [], and thus your JSON addressing will have to use [0] to get the data.

I suppose you could remove (replace) the [] from the string.

Eg this:

    Dim str As String = JsonConvert.SerializeObject(rstData)
    str = str.Replace("[", "")
    str = str.Replace("]", "")

    TextBox1.Text &= str

And now we have this:

在此处输入图像描述

So, above shows the one row, and without a json array of []

use this code:

System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
        if (sqlConnection.State == System.Data.ConnectionState.Closed)
        {
            await sqlConnection.OpenAsync();
        }
        System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand(SP_Name, sqlConnection);
        if (param != null)
        {
            for (int i = 0; i < param.Count; i++)
            {
                sqlCommand.Parameters.Add(param[i]);
            }
        }
        if (is_StoredProcedure)
        {
            sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
        }
        System.Data.SqlClient.SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync();
        System.Data.DataTable ret = new System.Data.DataTable();
        ret.Load(sqlDataReader);
        sqlDataReader.Close();
        sqlCommand.Dispose();
        sqlConnection.Close();
        sqlConnection.Dispose();
        List<dynamic> result = new List<dynamic>(ret.Rows.Count);
        foreach (System.Data.DataRow? row in ret.Rows.OfType<System.Data.DataRow>())
        {

            IDictionary<string, object>? expando = new System.Dynamic.ExpandoObject();

doesn't match target type. foreach (System.Data.DataColumn? col in row.Table.Columns.OfType<System.Data.DataColumn>()) { expando.Add(col.ColumnName, row[col]); } result.Add(expando); } return result;

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