Click here to Skip to main content
15,911,786 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created the web Application But i am unable to execute more than one line
protected void btnExecute_Click(object sender, EventArgs e)


string path = FileUpload1.PostedFile.FileName;//I am using FileUpload COntrol
System.IO.StreamReader sr = new System.IO.StreamReader(path);
string line;
string str = "";
int counter = 0;
while ((line = sr.ReadLine()) != null)
{
str = line;


counter++;
}
txtQuery.Text = str;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = txtQuery.Text;
cmd.Connection = conn;
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
sr.Close();
Posted

1 solution

Your while-loop overwrites on each iteration str with the last read line. So, when the loop is finished, str only contains the very last line of your file. You should instead append line to str and that's best done with a StringBuilder:
C#
string line;
StringBuilder sb = new StringBuilder();
int counter = 0;
while ((line = sr.ReadLine()) != null)
{
   sb.AppendLine(line);
   counter++;
}
txtQuery.Text = sb.ToString();

Note that this all only makes sense if you actually need the line-count of the file. Otherwise you could just read it all at once with sr.ReadToEnd()

Edit: You should use your StreamReader and your SqlCommand in a using-Block and supply the argument CommandBehavior.CloseConnection to your ExecuteReader-call.
 
Share this answer
 
v2
Comments
gaurav goyal 22-Apr-15 2:36am    
Hi Sascha Thanks for replying
I want to execute SQL file which contains multiple select statement.
How Can I do it?
Sascha Lefèvre 22-Apr-15 11:26am    
Hi Gaurav Goyal, you're welcome.

You can execute multiple select-statements as a batch and then use SqlDataReader.NextResult() to advance to the next result-set after reading the previous one. Plase take a look here:

http://csharp.net-informations.com/data-providers/csharp-multiple-resultsets.htm
http://stackoverflow.com/questions/14710903/returning-multiple-sql-query-results-c-sharp
gaurav goyal 27-Apr-15 1:49am    
Thanks... @Sascha
gaurav goyal 29-Apr-15 6:55am    
Hi Sascha I need to show result of these multiple select statements in separate gridview.How can I do that

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900