Read Data Values from specific row in SQL Server Table c#

Hemanth B 886 Reputation points
2021-11-07T09:12:49.157+00:00

Hi I am currently reading data from a table in DataBase.mdf with the following code:

   cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\bnara\source\repos\MyOnlineSchoolx86\MyOnlineSchoolx86\Questions.mdf;Integrated Security=True");
            cn.Open();
            cmd = new SqlCommand("select * from QuestionsTable", cn);

            dr = cmd.ExecuteReader(); dr.Read();
            label1.Text = dr["question1"].ToString();

Now this is actually reading question1 from the first row. I want it to read the value from a specified row number. How do I do that? I searched the Web, but didn't work.

Also this question is different: How can I create a connection to a database table in .Net 5.0? I guess the connection only works in .Net Framework.

Developer technologies C#
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-11-07T09:57:12.787+00:00

    For the connection and so forth open the .csproj file by double clicking it, add the following package reference for System.Data.SqlClient

    <Project Sdk="Microsoft.NET.Sdk">  
      
     <PropertyGroup>  
     <LangVersion>9.0</LangVersion>  
     <TargetFramework>net5.0</TargetFramework>  
     <IsPackable>false</IsPackable>  
     </PropertyGroup>  
      
     <ItemGroup>  
     <PackageReference Include="System.Data.SqlClient" Version="4.8.2" />  
     </ItemGroup>  
      
    </Project>  
      
    

    NuGet package or the newer package.

    About row number, there is no built in feature other than ROW_NUMBER

    Numbers the output of a result set. More specifically, returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

    Sample

    SELECT ROW_NUMBER() OVER(  
           ORDER BY CustomerIdentifier) AS Number,   
           CompanyName  
    FROM Customers  
    WHERE CustomerIdentifier > 4;  
    

    147063-figure1.png

    Now there is a half baked method I can present but first need to know a) is this a single user database? b) how many records?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.