Saturday, October 30, 2021

Database connectivity of Grid with ASP.Net(C#)

 >First add connection string to Web.config file (database name is aggregate)

<configuration>

<connectionStrings>

<add name="connectionString" connectionString="initial catalog=aggregate;user=sa1;password=sa;data source=." />

</connectionStrings>

</configuration>


>Add Grid to aspx page

<asp:GridView ID="GridView1" runat="server">

            </asp:GridView>


>Add below code to aspx.cs

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;


public partial class Webforms_Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        String conStr = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;


        using (SqlConnection con = new SqlConnection(conStr))

        {

            using (SqlCommand cmd = new SqlCommand("Select * from aggregate._form_info", con))

            {

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))

                {

                    DataTable dt = new DataTable();

                    da.Fill(dt);

                    GridView1.DataSource = dt;

                    GridView1.DataBind();

                }

            }

        }

    }

}


No comments:

Post a Comment