Trying to connect sql databse to aspnet for showing data in gridview with following codes, some issue in this code. Please any one solve this-
using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace gridview1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(@"datasource=DESKTOP-66R7QLC; nitial catalog = SqlPractice; integrated security=sspi");
//con.Open();
//SqlCommand cmd = new SqlCommand("select * from Tbl_Employee", con);
//SqlDataReader rdr = cmd.ExecuteReader();
////GridView1.datasource = rdr;
//GridView1.DataBind();
//con.Close();
string connectionString = "Data Source=DESKTOP-66R7QLC;Initial Catalog=SqlPractice";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string query = "SELECT * FROM Tbl_Employee";
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
connection.Close();
}
}
}
Cr BhargaviPosted Sep 21, 2023, 9:16 AM
Rajeev KumarPosted Sep 21, 2023, 5:16 AM
Prasad RaveendranPosted Sep 20, 2023, 7:08 PM
The code you've provided seems mostly correct for connecting to an SQL database and binding the data to a GridView in an ASP.NET web application. However, there's a minor issue in your connection string. Instead of "datasource," it should be "Data Source." Also, there's a typo in "initial catalog"; it should be "Initial Catalog."
Here's the corrected code:
Make sure that:
Also, consider adding error handling to the code to properly handle exceptions that may occur during database operations.
Cr BhargaviPosted Sep 20, 2023, 10:23 AM
Amit MohantyPosted Sep 20, 2023, 5:37 AM
I think there might be an issue with your connection string. Try this:
Full Code:
Ajay KumarPosted Sep 20, 2023, 4:30 AM
It looks like you have commented out some code and made some minor mistakes in your C# code for connecting to a SQL database and populating a GridView. Here's a corrected version of your code:
Here are the changes made:
The connection string should include
Integrated Security=Trueto use Windows Authentication.We added a
try-catchblock to handle any exceptions that might occur during database operations.In the
catchblock, you can handle exceptions by displaying an error message or logging the error.With these changes, your code should now work correctly to connect to the SQL database, fetch data from the
Tbl_Employeetable, and bind it to the GridView. Make sure your SQL Server instance is running and that the database and table names are correct.