Saturday, October 18, 2014

Dispaly table records to gridview using c# .net

simple telerick grid and dispaly the database table values using c# .net
------------------------------------------------------------------------------------


simple 3 steps:

1)btnSave_Click 'button click
2)GetDataTable(parameter is query here)  ' calling function from grid
3)DataTable GetDataTable(string query)   ' defination of above function

or if you want to show the table separtely write code in view button.


step 1):
-------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace myFirstOfficeDemo
{
    public partial class alert : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

            string str = "Data Source=.;Initial Catalog=alertDb;Integrated Security=True";
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand com = new SqlCommand("SP_ADD_ALERT", con);
            com.Parameters.Add("@header", SqlDbType.VarChar).Value = txtHeader.Text;
            com.Parameters.Add("@text", SqlDbType.VarChar).Value = txtText.Text;
            com.CommandType = CommandType.StoredProcedure;
            com.ExecuteNonQuery();
            string script = "alert('Saved');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true);
            con.Close();
            txtHeader.Text = "";
            txtText.Text = "";
        }

        'protected void btnView_Click(object sender, EventArgs e)
        '{
        '  
        '}




step 2):
-------

       public void RadGrid1_NeedDataSource1(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = GetDataTable("SELECT alertId, header, text FROM utilAlert");
        }


step 3):
-------
        public DataTable GetDataTable(string query)
        {
            String ConnString = ConfigurationManager.ConnectionStrings["alertDbConnectionString"].ConnectionString;
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataTable myDataTable = new DataTable();
            using (SqlConnection conn = new SqlConnection(ConnString))
            {
                adapter.SelectCommand = new SqlCommand(query, conn);
                adapter.Fill(myDataTable);
            }
            return myDataTable;
        }

     
    }
}

No comments:

Post a Comment