Home > Software design >  How to get read multiple rows in single column Data?
How to get read multiple rows in single column Data?

Time:10-19

I have 7 Textboxes, and Data i have to fetch from Single col and 7 rows and assign to the 7 textboxes,

E.g

DefectStatus
None
None
None
}
    OldbCommand = new OleDbCommand("SELECT DefectStatus FROM TblProductionData WHERE SerialNumber='"   TxtSerialNo.Text.Trim()   "'", ClsGlobals.con);
            OldbReader = OldbCommand.ExecuteReader();
}

        
while ( OldbReader.Read())
{
    TxtCell1Status.Text = OldbReader.GetValue(0).ToString();
    TxtCell2Status.Text =  I dont know how to get value from second row
 
}

CodePudding user response:

List<TextBox> listOfTextBoxes = new List<TextBox>();
listOfTextBoxes.Add(TxtCell1Status);
listOfTextBoxes.Add(TxtCell2Status);
listOfTextBoxes.Add(TxtCell3Status);
listOfTextBoxes.Add(TxtCell4Status);
listOfTextBoxes.Add(TxtCell5Status);
listOfTextBoxes.Add(TxtCell6Status);
listOfTextBoxes.Add(TxtCell7Status);

int count = 0;
while ( OldbReader.Read())
{
    listOfTextBoxes[count].Text = OldbReader.GetValue(0).ToString()
    count  ;
}

I DID NOT VERIFY THIS BUILDS - TREAT IT AS PSEUDO CODE.

The problem here is you NEED to know how many results you will get, or your UI will likely fail to display the required data, or just throw an exception.

You should use a gridview instead, and assign your result as a data source.

Also this code is heinously dirty. You should initialise objects, away from logic, you should make your code way more readable.

So treat this code with all the contempt it deserves.

CodePudding user response:

var textBoxes = new[]
                {
                    TxtCell1Status,
                    TxtCell2Status,
                    TxtCell3Status,
                    ...
                }

foreach (var tb in textBoxes)
{
    OldbReader.Read();
    tb.Text = OldbReader.GetString(0);
}

This assumes that there will always be at least as many rows as there are TextBoxes.

  •  Tags:  
  • c#
  • Related