I am working on a code in C#.NET to create a web service that will take in a particular input. It will then connect to the database , where depending on the input provided, the entire result must be fetched from my table and displayed accordingly.
However, I am not that familiar with C#.NET and so I am not able to implement my code properly. can someone please help me
Here is what I have do so far:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace test3
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public String GetAttendance(String rollno)
{
String result="";
try
{
using (SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123"))
{
myConnection.Open();
using (SqlCommand myCommand = new SqlCommand())
{
myCommand.Connection = myConnection;
myCommand.CommandText = "SELECT COUNT(*) FROM studentdata WHERE rollno = @rollno";
myCommand.Parameters.Add("@rollno", SqlDbType.VarChar).Value = rollno;
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
result = myReader.ToString();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "an error occured";
}
return result;
}
}
}
If I run this code, I get output as “System.Data.SqlClient.SqlDataReader” which is not what i want
Don’t use a data reader for this you only have one result which is a row count so use
ExecuteScalar()and use an int as type for result:(Alternatively you can get the string value with your current query using
result = myReader.GetInt32(0).ToString();– don’t do this though)