0

I have a small DataTable that contains a number of rows which I am running a LINQ query against.

I am having problems getting the LINQ to display the text that is in the datatable.

When I run it I can get the column name.

I have tried a number of different ways of doing it but to no avail.

Code as follows:

DataTable DTGetNarratives = DAL.GetNarrativeList();

var SelectedNarrative = 
    from n in DTGetNarratives.AsEnumerable()
    where n.Field<string>("narr_code").Equals(ClsPublic.NarrativeCode)
    select n;

foreach (var item in SelectedNarrative)
{
    //test1.Add(item.Table.Columns[col].ToString());
    //col++;

    txtLine1.Text = item.Table.Columns[0].DefaultValue.ToString();
}

Any help on this would be great.

1
  • Which control do you plan to use to display? You can either set the binding straight to the "SelectedNarrative", or append(+=) to the TextBox. Commented Nov 25, 2013 at 16:51

2 Answers 2

2

So you have one TextBox but an IEnumerable<DataRow>. Do you expect a single row? If not, how do you want to diplays multiple records on a single textbox?

You could comma separate them:

var allNarrCode = SelectedNarrative.Select(r => r.Field<string>("narr_code"));
txtLine1.text = string.Join(",", allNarrCode); 

or as multiline TextBox use the Lines property:

txtLine1.Lines = allNarrCode.ToArray();

Only the first:

txtLine1.Text = SelectedNarrative.FirstOrDefault();

without LINQ:

foreach (DataRow row in SelectedNarrative)
{
   string code = row.Field<string>("narr_code")
   // the next line is pointless since you're overwriting the text on every row
   //txtLine1.Text = code;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the Field extension method like:

foreach (var item in SelectedNarrative)
{
   txtLine1.Text = item.Field<string>("narr_code"); //here
}

(You can specify the column name in the method parameters)

I am not sure if you really need that since your TextBox would be populated with the last row's value.

To show all values in a single TextBox you can do:

txtLine1.Text = string.Join(" ",SelectedNarrative.Select(r=> r.Field<string>("narr_code")));

Or you can do

StringBuilder sb = new StringBuilder();
foreach (var item in SelectedNarrative)
{
  sb.Append(item.Field<string>("narr_code"));
}
txtLine1.Text = sb.ToString();

1 Comment

But OP has already used it in the query and you're overwriting the text always in the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.