none
fill data table using sqlcommend

    Question

  • i can fill a data table using SqlDataAdapter ... 

    but i want to use sqlcommend instand of SqlDataAdapter then how can i do that

    Thursday, March 30, 2017 9:55 PM

All replies

  • Hello,

    Simple example, we have a table named Customers, we want all customer AccountNumber were the field Country is equal to say Canada. So when calling this function we pass in Canada. It's always best to use parameters as shown below rather than string concatenation.

    You need to setup the connection string, look to the following page for how to create the connection string.

    public DataTable Demo1(string Country)
    {
        var dt = new DataTable();
        using (SqlConnection cn = new SqlConnection { ConnectionString = "Your connection string goes here" })
        {
            using (SqlCommand cmd = new SqlCommand { Connection = cn })
            {
                cmd.CommandText = "SELECT AccountNumber FROM Customers WHERE Country=@Country";
                cmd.Parameters.AddWithValue("@Country", Country);
                cn.Open();
                dt.Load(cmd.ExecuteReader());
            }
        }
    
        return dt;
    }
    So that is the basic setup for returning data using a where condition. You can add more fields to the SELECT and more conditions to the WHERE as needed.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, March 30, 2017 10:35 PM
    Moderator