Ghost_Programmer Ghost_Programmer - 1 year ago 39
SQL Question

SQL table result command in textbox instead of the result in C#

Here is the table setup I have:

int | Design_1
0 | Design_A
1 | Design_B
2 | Design_C

Here is my code for the form:

var design = (from d in BikePartsDataContext1.handlebars
where d.@int == "0"
select d.Design_1);
this.textBox1.Text = design.ToString();

What I am trying to do is make the
text have the value of the
value from the row where
is 0.

All works fine until I get this as the text value for

SELECT [t0].[Design 1] FROM [dbo].[handlebars] AS [t0] WHERE [t0].[int] = @p0

Answer Source

I think you want the first record then based on Id?

// at top of file so you can use the extension methods
using System.Linq;

// code
var design = (from d in BikePartsDataContext1.handlebars
              where d.@int == 0 // i removed the quotes add them back if this is truely a string/sql varchar
              select d.Design_1).Single(); // use single to ensure only 1 record will get selected
this.textBox1.Text = design; // design will now be the value of Design_1

Some notes:

  • Single will throw an exception if no records are found OR if more than one record is found.
  • If there can be 0 records use SingleOrDefault
  • If there can be more than 1 record and you do not care which one is used then use First or FirstOrDefault
  • I assumed your id was an int and not a string so I removed the quotes around 0, add them back if this is not the case

You can also rewrite it using only lambda expressions:

this.textBox1.Text = BikePartsDataContext1.handlebars
    .Where(x => x.@int == 0)
    .Select(x => x.Design_1)