S.A. Khalili S.A. Khalili - 4 months ago 26
ASP.NET (C#) Question

Show LINQto sql table rows in separate text boxes

I have an array where it gets its data from a LINQ to sql query. I am using ASP.NET Webforms.

We say I have following table:

ID fltNVR fltNamn
1 75 Kam1-75
2 75 Kam2-75
3 75 Kam3-75
4 75 Kam4-75
5 76 Kam1-76
6 76 Kam2-76
7 76 Kam3-76

using (myDataContext sls = new myDataContext())
IQueryable<tblNVRChannel> channels= (from channel in sls.tblNVRChannels
where kanal.fltNVR == 75
select channel);
tblNVRChannel[] kanArray = channels.ToArray();
foreach (var item in channelArray)
TextBox1.Text = item.fltNamn;
TextBox2.Text = item.fltNamn;
TextBox3.Text = item.fltNamn;
TextBox4.Text = item.fltNamn;
TextBox5.Text = item.fltNamn;

Using above query I get the values from the table but I cannot show each item in separate textboxes, what I get is the last item of the query (Kam4-75) in each textbox, but I want Kam1-74 in textbox1, kam2-75 in textbox2 and so on.

There are some examples using firstordefault() but when I tried it I get only the first row which does not work for me, though I am not sure.

Populating textboxes using LINQ2SQL
and Linq to Sql: How to Fetch specific row using store procedure and display columns data into textboxes

I tried to assign textbox.text data using a loop but I could not.
I want something like below in final result:

TextBox1.Text = kam1-75;
TextBox2.Text = kam2-75;
TextBox3.Text = kam3-75;
TextBox4.Text = kam4-75;
TextBox5.Text = NULL;


Unless you use reflection/if else statements/switch cases then a loop will not help. What you should do is just directly assign:

string defaultValue = string.Empty;

TextBox1.Text = kanArray.EelementAtOrDefault(0) ?? defaultValue; // kam1-75
TextBox2.Text = kanArray.EelementAtOrDefault(1) ?? defaultValue; // kam2-75
TextBox3.Text = kanArray.EelementAtOrDefault(2) ?? defaultValue; // kam3-75
TextBox4.Text = kanArray.EelementAtOrDefault(3) ?? defaultValue; // kam4-75
TextBox5.Text = kanArray.EelementAtOrDefault(4) ?? defaultValue; // ""
// If you prefer null then just remove all the ?? operator

The use of ElementAtOrDefault will return the item in position X and default(TSource) if such position does not exist. The default value for string is null so you can use the ?? to set a different "default value"