5

I have table which has composite keys in order to retrieve data from two different tables. I have created stored procedures to do that and it works fine:

Stored procedure:

ALTER PROC dbo.spp_adm_user_user_group_sel
AS 
BEGIN 
    SET NOCOUNT ON

    SELECT 
        g.name AS Group_Name, u.fullname, u.designation, 
        u.email, u.mobile 
    FROM 
        TBL_ADM_USER_GROUP g, TBL_ADM_USER u
    WHERE 
        g.id = u.group_id 
        AND (g.deleted IS NULL OR g.deleted <> 1)
END

The result is like this:

Group_name  fullname    designation  email          mobile
Alex        fffffffff   Engineer     [email protected]  3333333333
Jon        hhhhhhhhh    programmer   [email protected]    020202028347

As you can see, the stored procedure does not have any parameters. How to read this output and return it as list using C#?

Code:

public List<string> GetData()
{
    using (SqlConnection con = new SqlConnection(Global.Config.ConnStr))
    {
        string group;

        DataTable dt = new DataTable();
        List<string> details = new List<string>();

        SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
            details.Add(group);
        }
    }

    return details;
}
11
  • I have done some code to do that but it requires parameter, but as you can see my stored procedures does not have any parameter. So my code is not useful anymore and that why I dont paste it here
    – Saif
    Nov 24, 2015 at 1:26
  • Please do add it to your question (edit) so we know which technology you prefer. Nov 24, 2015 at 1:28
  • I have pasted C# code,
    – Saif
    Nov 24, 2015 at 1:31
  • 1
    Yes it can be done .. but I am asking what do you want to structure of the list to look like..? if you want it to mimic the structure of the query then you should create a Class that has the following auto propertys Group_name fullname designation email mobile then make a List<Class> and populate the List<Class> field remembering to Add as well as creating a new instance of that class that you will add to your List<T>
    – MethodMan
    Nov 24, 2015 at 2:12
  • 1
    the add the code that will either Join the values with , look up string.Join() method.. or create an instance of a List<T> and while you are in the loop get at the datatable's ItemArray start using the debugger and you will see you are almost there..
    – MethodMan
    Nov 24, 2015 at 2:21

3 Answers 3

3

Change your code to this

public List<yourClass> GetData()
{
using (SqlConnection con = new SqlConnection(Global.Config.ConnStr))
{

    DataTable dt = new DataTable();
    List<yourClass> details = new List<yourClass>();

    SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);
    cmd.CommandType = CommandType.StoredProcedure;

    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dt);

     foreach(DataRow dr in dt.Rows)
            {
                yourClass obj = new yourClass();

                obj.fullname= dr["fullname"].ToString();
                obj.email= dr["email"].ToString();

                details.Add(obj);
            }


            return details;
        }

}

3

If You Got The Code To Execute Store Procedure,and

SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);

Code Returning Your Desired Result In Dt,Then You Can Just Try Something like That.

 foreach (DataRow dr in dt.Rows)
        {
            details.Add(dr.Field<String>("Your_Coumn_Name_In_Dt"));
        }

Or

foreach (DataRow dr in dt.Rows)
            {
                details.Add(Convert.ToString(dr[0]));// 0 is the Column Index
            }

Returning A DetailList,

Way1: create a Model Class that contains your properties and return list of that model Class.

public class Details{
     public string Group_name  {get;set;}
     public string fullname { get; set; }
     public string designation { get; set; }
     public string email{ get; set; }
     public string mobile{ get; set; }

} 

And Change Your Method.

public List<Details> GetData()
{
    using (SqlConnection con = new SqlConnection(Global.Config.ConnStr))
    {

        DataTable dt = new DataTable();
        List<Details> details = new List<string>();

        SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
           Details group=new Details();

            group.Group_name  =dr.Field<string>("Group_name");
            group.fullname =dr.Field<string>("fullname");
            group.designation =dr.Field<string>("designation");
            group.email=dr.Field<string>("email");
            group.mobile=dr.Field<string>("mobile");

            details.add(group);
        }
    }

    return details;
}

Way2: If You Don't Want To Create A Model Then a bad solution will be to return a list of objects

 public List<Object> GetData() {
using (SqlConnection con = new SqlConnection(Global.Config.ConnStr))
        {

            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);


        var result = from o in dt.AsENumerable()
                     select (new
                     {
                        Group_name  =dr.Field<string>("Group_name"),
                        fullname =dr.Field<string>("fullname"),
                        designation =dr.Field<string>("designation"),
                        email=dr.Field<string>("email"),
                        mobile=dr.Field<string>("mobile")
                     } as Object);

        }

        return result.ToList();
    }
3
  • how to return details ?
    – Saif
    Nov 24, 2015 at 6:39
  • Wait, Let me Update My Answer.
    – A_Sk
    Nov 24, 2015 at 6:45
  • i Can't Understand Urdu or Arabic, You Need To Write In English.@Smart
    – A_Sk
    Nov 24, 2015 at 6:53
0

you can call the stored procedure and take the result into a dataset.

        SqlConnection Cn = new SqlConnection("Constr");
        SqlCommand Cmd = new SqlCommand("StoredProcName", Cn);
        SqlDataAdapter Da = new SqlDataAdapter(Cmd);
        DataSet Ds = new DataSet();
        Da.Fill(Ds, "TableName"); //Da.Fill(Ds);

Copy the rows of the data table to an array using CopyTo method of Rows collection of Data table and then convert it into list. Of course the List type will be DataRow and not any custom class.

        DataTable Dt = Ds.Tables["TableName"]; // DataTable Dt=Ds.Tables[0];
        DataRow[] Array = new DataRow[Dt.Rows.Count];
        Dt.Rows.CopyTo(Array, 0);
        List<DataRow> List=Array.ToList();            

if you want to use a custom class then create the class and convert this List of type DataRow to List of type CustomClass as follows.

        List<customclass> List1=new List<customclass>();
        foreach(var L in List)
        {
             CustomClass C=new CustomClass();
             C.Field1=L[0].ToString();
             C.Field2=int.Parse(L[1].ToString());
             .....//Assign values to all fields in the custom class 
             List1.Add(C);
        }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.