Alex S
Alex S

Reputation: 11

How to convert query results to string c#

I am storing HTML in a varchar(max) field there can be many of these fields returned in a data set I need to basically concat them into a string so I can add them to my control any idea's?

so for example

result 1: <h5> This is a result  </h5>
result 2: <h5> This is a result  </h5>
result 3: <h5> This is a result  </h5>
result 4: <h5> This is a result  </h5>

I need the results set to be parsed to a string that would be like:

<h5> This is a result  </h5>
<h5> This is a result  </h5>
<h5> This is a result  </h5>
<h5> This is a result  </h5>

I am returning the result from a stored procedure because I will be allowing the user to only execute stored procedures and they will not have any table permissions

Upvotes: 1

Views: 1677

Answers (4)

webtrifusion
webtrifusion

Reputation: 4556

If I understand the question correctly, your HTML will be in the database and needs to be rendered in the control? If yes, I would setup a literal control and when loading the data, set the property of the literal to render the stored HTML results.

StringBuilder sb = new StringBuilder();
for(int i = 0; i < dsResults.Tables[0].Rows.Count - 1; i++)
{
    sb.Append(PrepareResult(dsResults.Tables[0].Rows[i][0].ToString()));
}

litControl.Text = sb.ToString();


public string PrepareResult(string result)
{
    return result.Substring(result.IndexOf("<"));
}

This is free hand code, so you may need to adjust slightly, I think the concept is clear. HTH

Upvotes: 1

Frank Pearson
Frank Pearson

Reputation: 872

In a SQL Stored Procedure you could do the following

DECLARE @PartHTML VARCHAR(MAX)
DECLARE @FullHTML VARCHAR(MAX)

DECLARE CURSOR HTMLCursor FOR (SELECT FieldWithHTML FROM TableWithHTML)
OPEN CURSOR HTMLCursor

FETCH NEXT FROM HTMLCursor INTO @PartHTML

While (@@FETCH_STATUS <> -1)
BEGIN
    SET @FullHTML = @FullHTML + @PartHTML + CHAR(13)
    FETCH NEXT FROM HTMLCursor INTO @PartHTML

END
CLOSE HTMLCursor
DEALLOCATE HTMLCursor

Upvotes: 0

Lawrence Wagerfield
Lawrence Wagerfield

Reputation: 6611

You could use LINQ:

string[] results = ...
string resultsStr = results.Aggregate((a,b) => a + b);

or...

MyEntity[] results = ...
string resultsStr = results.Select(r => r.SomeColumn).Aggregate((a,b) => a + b);

Upvotes: 0

ean5533
ean5533

Reputation: 8994

string results = someStoredProcCall();
results = Regex.Replace(results, @"result [0-9]+: ", "");

Upvotes: 1

Related Questions