I have created a Label control and gridview. Label shows the data but In Gridview data from database does not populate.
Following is my code. No error is received while doing this
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select BATSMAN_NAME from RUNS_STATS", con);
con.Open();
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{
Label1.Text = dr.GetString(dr.GetOrdinal("BATSMAN_NAME"));
}
GridView2.DataSource = dr;
GridView2.DataBind();
con.Close();
}
}
}
Use SqlDataAdapter & dataset to fill gridview
SqlCommand cmd = new SqlCommand("Select BATSMAN_NAME from RUNS_STATS", con);
SqlDataAdapter daGrid = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
daGrid.Fill(ds);
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
Try disconnected architecture. Incase the following code doesn't work, check if the Query is appropriate.
SqlConnection conobj=new SqlConnection;
SqlCommand cmdobj=new SqlCommand(""Select BATSMAN_NAME from RUNS_STATS", conobj);
SQlDataAdapter sdaobj=new SqlDataAdapter(cmdobj);
DataTable dtobj=new DataTable();
sdaobj.Fill(dtobj);
GridView2.DataSource=dtobj;
GridView2.DataBind();
Related
im trying to follow a basic asp.net videos: https://www.youtube.com/watch?v=9e0kwADEoEg to create a web page that has a textbox, button and gridview.
For some reason the gridview will never show with populated data :/ I think its because of the .fill but really not sure. I can see the query when running a trace on sql server. just no output on the webpage!? Can anyone assist?
ausing 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;
public partial class _Default : System.Web.UI.Page
{
SqlConnection vid = new SqlConnection("Server=localhost;Database=exam;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string str = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = '#search'";
SqlCommand xp = new SqlCommand(str,vid);
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
GridView1.DataSource = ds;
GridView1.DataBind();
vid.Close();
}
}
Get rid of the single quotes in the query:
string str = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = #search";
The quotes tell Sql Server to treat #search as a string literal instead of an sql variable name.
Additionally, get rid of the ExecuteNonQuery() code. That function is for INSERT/UPDATE/DELETE statements.
Another issue is the SqlConnection object. Don't try to re-use the SqlConnection object in your page. .Net uses a feature called connection pooling to cache the underlying connection object, and trying to re-use the same .Net SqlConnection object instance conflicts with that. Just keep the connection string handy and create a new SqlConnection instance. Really.
There's more, too. The code below makes a number of other improvements: using so things are cleaned up in case of an exception, Fill() will open and close the connection for you, binding to a specific table, etc...
private const string cnString = "Server=localhost;Database=exam;Integrated Security=True";
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = #search";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(cnString))
using (SqlCommand xp = new SqlCommand(sql, con))
using (SqlDataAdapter da = new SqlDataAdapter(xp))
{
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
da.Fill(ds, "Name");
}
GridView1.DataSource = ds.Tables["Name"];
GridView1.DataBind();
}
// Open connection
using (SqlConnection c = new SqlConnection(vid))
{
c.Open();
// 2
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter(
"SELECT * FROM EmployeeIDs", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
dataGridView1.DataSource = t; // <-- From your designer
}
}
I am currently working on a forum project using a gridview to attached the data to the database. Using SelectedIndexChanged, it will redirect to another page to display the details in labels. However, I am unable to display & there isn't any specific error.
This is my code:
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 FAQViewPost : System.Web.UI.Page
{
string _connStr = ConfigurationManager.ConnectionStrings["WingsDrinksDbContext"].ConnectionString;
FAQ faq = null;
string CustQuestionCategory = null;
string CustQuestion = null;
protected void Page_Load(object sender, EventArgs e)
{
string FAQID = Request.QueryString["FAQID"].ToString();
Load(FAQID);
}
protected void Load(string FAQID)
{
DataTable dt = new DataTable();
string queryStr = "SELECT * FROM [FAQ] WHERE FAQID = #FAQID ";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand();
string[] arr = { queryStr };
string allQueries = string.Join(";", arr);
cmd.CommandText = allQueries;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#FAQID", FAQID);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
lbl_category.Text = dt.Rows[0]["CustQuestionCategory"].ToString();
lbl_question.Text = dt.Rows[0]["CustQuestion"].ToString();
}
conn.Close();
conn.Dispose();
}
}
I do not know why you are putting the SQL into an array. You only have one statement. Try using just:
DataTable dt = new DataTable();
string queryStr = "SELECT * FROM [FAQ] WHERE FAQID = #FAQID ";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = queryStr;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#FAQID", FAQID);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
I presume you have checked that the FAQ table has a record for the id you are sending? Also life would be a bit safer if you used numeric ids.
I cant see the dropdown list I created (click this link for image)
Here is my code in add.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//ADO.NET
using System.Data;
using System.Data.SqlClient;
using System.IO;
public partial class Admin_Users_Add : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(kmb.GetConnection());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategoryTypes();
}
}
/// <summary>
/// Allows the user to display list of user types
/// from the table Types to the dropdownlist control
/// </summary>
void GetCategoryTypes()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT CatID, Category FROM Categories";
SqlDataReader dr = cmd.ExecuteReader();
ddlCategoryTypes.DataSource = dr;
ddlCategoryTypes.DataTextField = "Category";
ddlCategoryTypes.DataValueField = "CatID";
ddlCategoryTypes.DataBind();
ddlCategoryTypes.Items.Insert(0, new ListItem("Select one...", ""));
con.Close();
}
}
In database I created 2 tables:
Categories(CatID [PK], Category[FK])
CategoryTypes(Category [PK], Appetizers, Desserts, Beverages)
---- I want to see the "Appetizers, Desserts, Beverages" in the dropdown list which is from database, in my webpage
You need to change the query to:
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT CatID, Appetizers +', '+ Desserts +', '+ Beverages as CatDescription FROM Categories Inner Join CategoryTypes ON Categories.Category = CategoryTypes.Category";
SqlDataReader dr = cmd.ExecuteReader();
ddlCategoryTypes.DataSource = dr;
ddlCategoryTypes.DataTextField = "CatDescription";
ddlCategoryTypes.DataValueField = "CatID";
ddlCategoryTypes.DataBind();
ddlCategoryTypes.Items.Insert(0, new ListItem("Select one...", ""));
con.Close();
I am generating simple Crystal Report in VS-2012 from SQL Server 2014, unfortunately it is not loading/showing content in the browser. Showing no error.
What I did is, added Project, Added crystal report and configured with SQL Server database, drag and drop items, preview in visual studio is show correctly as data is in SQL Server. I haven't added any extra Dataset or DataTables becuase I am gettinf my data directly from SQL server
Here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace CrystalReports
{
public partial class ShowReports : System.Web.UI.Page
{
//SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CrystalReportViewer1.Visible = false;
//CrystalReportViewer1.RefreshReport();
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
ReportDocument myReportDocument = new ReportDocument();
string reportPath = Server.MapPath(#"CrystalReport1.rpt");
myReportDocument.Load(reportPath);
string constring = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
string query = "SELECT * FROM tblCustomer";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
adp.Fill(dt);
myReportDocument.SetDataSource(dt);
CrystalReportViewer1.ReportSource = myReportDocument;
CrystalReportViewer1.Visible = true;
}
}
}
I am trying to insert data from text box to sql database, but I want to check if the row is empty then insert new value else update the row with the values with sqlcommands in if else condition.
Below is my code:
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;
public partial class CM : System.Web.UI.Page
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlCommand cmd;
//DataTable dt;
SqlConnection con = new SqlConnection("server =consulting76\\SQLEXPRESS; database = msdb; Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter();
//("Select * from NOTESMAKER", con);
//da.Fill(ds, "NOTESMAKER");
//dt = ds.Tables["NOTESMAKER"];
}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
if (DBNull.Value != null)
{
cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
else
{
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.UpdateCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}
}
if you don't know how to fired a select query, have a look here
select * from tablename where columnName is not null
fill sqldataadapter from your query eg
if dataset count is zero then you may proceed with insert operation else update.
if (ds.table[0].rows.count==0)//insert
{
}
else// update
}
You can do it this way. ExecuteNonQuery() returns the number of affected rows, so if insert returns 0, it means that there was nothing to update. Hence you need to insert a row.
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
int affectedRows = cmd.ExecuteNonQuery();
if (affectedRows == 0)
{
cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
cmd.ExecuteNonQuery();
}