Sunday, 25 March 2012

GridView: how to save the selected value of the dropdownlist?

I'm using a simple gridview and sqldatasource to bind the data from database to the gridview.
Options: Paging,sorting,editing.

2 comments:

  1. CREATE TABLE [DBO].[TEST](
    ID INT PRIMARY KEY IDENTITY(1,1),
    NAME VARCHAR(50),
    EMAIL VARCHAR(50),
    PHONE VARCHAR(50)
    )

    ReplyDelete
  2. using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;

    public partial class _Default : System.Web.UI.Page
    {
    SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["GridView"].ConnectionString);
    SqlCommand sqlcom;
    SqlDataAdapter sqladp;
    DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    BinGridView();
    }
    }

    void BinGridView()
    {
    using (sqlcom = new SqlCommand("SELECT * FROM [DBO].[TEST]", sqlcon))
    {
    sqladp = new SqlDataAdapter(sqlcom);
    dt = new DataTable();
    dt.Clear();
    sqladp.Fill(dt);
    if (dt.Rows.Count > 0)
    {
    GdBind.DataSource = dt;
    GdBind.DataBind();
    }
    else
    {
    Response.Write("Data Not Found");
    }
    }
    }
    protected void GdBind_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
    sqlcon.Open();
    int id = int.Parse(GdBind.DataKeys[e.RowIndex].Value.ToString());
    GridViewRow grv = GdBind.Rows[e.RowIndex];
    TextBox TxtNm = (TextBox)grv.FindControl("TxtName");
    TextBox TxtEm = (TextBox)grv.FindControl("TxtEml");
    TextBox TxtPh = (TextBox)grv.FindControl("TxtPhn");
    using (sqlcom = new SqlCommand("UPDATE [DBO].[TEST] SET NAME='" + TxtNm.Text + "', EMAIL='" + TxtEm.Text + "', PHONE = '" + TxtPh.Text + "' WHERE ID='" + id + "' ", sqlcon))
    {
    sqlcom.ExecuteNonQuery();
    Response.Write("Update SucsessFully");
    GdBind.EditIndex = -1;
    BinGridView();

    ReplyDelete