Reputation: 21
How would I DataBind
a SQL 2005 database to a GridView
in a Button OnClick();
event?
I would also like to display the data in a table format.
Upvotes: 1
Views: 7063
Reputation: 3671
It will be good if you will start learning the basic ADO.NET as it fun! This is the sample for your doubt, hopw this might help. ASP.Net Bind GridView to DataTable
If you want to learn through flow (means creating connection, then using objects and methods created in Data Access Layer, Business Layer, using in the code behind) then you can ask.
Upvotes: 0
Reputation: 8630
Maybe you need to start of by learning ADO.NET, communicating with databases using SQL Data Adapters.
Using a Data Adapter you can populate DataTable's with records from the SQL Database.
In order to use your Data Table's with Gridview, your best off looking into Binding Objects.
I use a Binding Source, that binds the DataTable and Gridview together, and changes made in the DataTable will reflect automatically in the GridView.
There are millions of examples of this all over the internet.
Hope this gets you looking in the right direction.
Upvotes: 0
Reputation: 11144
this is a sample code might it helps you..
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="BasicGridView" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class BasicGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
string selectSQL = "SELECT ProductID, ProductName, UnitPrice FROM Products";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Products");
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
File: Web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="Northwind" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI"/>
</connectionStrings>
</configuration>
Read this another article for reference ..
Upvotes: 4