Get data from Sql Stored Procedure to grid view control using c#


1. Create stored procedure in sql server with select query (with or with out input parameters).
2. Create windows application or web application in VS 2010.

private void btnGetData_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = GetData();
          

        }


public static SqlConnection NewConnection()
        {
            string ConnectionString = @"server=*****; uid=***; pwd=****;                  database=*****;";
            return new SqlConnection(ConnectionString);
        }


public static DataTable ExecuteCommand(SqlCommand cmd)
        {
            try
            {
                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
            catch (SqlException ex)
            {
                throw new Exception(ex.Message);
            }
        }


public DataTable GetData()
        {
         
            try
            {
                SqlConnection con = NewConnection();
                string CommandText = "sp_EmployeeProcedure";
                SqlCommand cmd = new SqlCommand(CommandText, con) 
                { CommandType = CommandType.StoredProcedure };
                var myCi = new CultureInfo("en-US");
//if your procedure has any input parameters use this commented code.                
//cmd.Parameters.Add("@processType", SqlDbType.VarChar).Value = processType;               
                return ExecuteCommand(cmd);

            }
            catch (Exception ex)
            {
                ex.Message.ToString();

                return null;
            }
        }




!!!Please give your comments back on this.

Comments

Popular posts from this blog

Difference Between Site Template and Site Definition

Delete multiple site collections using SharePoint Power Shell Script

Managed Metadata Configuration and Association