It is popping an exception saying I can not using paging on the server side.
conn.Open();
string querstring = "select * from gt_transaction_log where LogTimeStamp between '2013-09-19 07:06:00.077' and '2013-09-19 10:28:25.163' ";
SqlCommand cmd = new SqlCommand(querstring, conn);
GridView1.EmptyDataText = "no record found";
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
GridView1.AllowPaging = true;
GridView1.PageSize = 5;
You cannot use paging with a DataReader. So problem is with this line:
GridView1.DataSource = cmd.ExecuteReader();
You should fill GridView using a Dataset or a Datatable using a DataAdapter.
Example:
// Using DataTable
string querstring = "select * from gt_transaction_log where LogTimeStamp between
'2013-09-19 07:06:00.077' and '2013-09-19 10:28:25.163' ";
SqlDataAdapter adapter = new SqlDataAdapter(querstring , conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource=dt;
GridView1.DataBind();
// Using DataSet
string querstring = "select * from gt_transaction_log where LogTimeStamp between
'2013-09-19 07:06:00.077' and '2013-09-19 10:28:25.163' ";
SqlDataAdapter adapter = new SqlDataAdapter(querstring , conn);
DataSet ds = new DataSet();
adapter.Fill(ds, "Table_Name"); // you can supply a table name
GridView1.DataSource=ds;
GridView1.DataBind();
You must specify if you want paging in the UI of the page, that is :
<asp:GridView ID="grid" runat="server" AllowPaging="true" PageSize="5" OnPageIndexChanging="grid_PageIndexChanging" />
Then in the cs file:
protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
grid.PageIndex = e.NewPageIndex;
BindGrid();
}
catch (Exception ex)
{
}
}
Where BindGrid() method is the one in which we bind the grid.
on design view , click Gridview > allow paging
or use SQLdatasource instead, then allow paging
You can try using this code.......
String constring = "Data Source=dsdsdsds;Initial Catalog=table;User Id=uid;Password=pass";
SqlConnection conqav = new SqlConnection(constring);
String takeffty = "select top 10 * from table";
conqav.Open();
SqlCommand comqav = new SqlCommand(takeffty,conqav);
GridView1.DataSource = comqav.ExecuteReader();
GridView1.DataBind();
conqav.Close();
Related
I want to show content of a table("newexample") in my database in SQL server to gridview in ASP.net, but the gridview shows nothing. How to fix it?
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string cs = ConfigurationManager.ConnectionStrings["SampleDBCS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select * from newexample", con);
DataTable dt = new DataTable();
dt.Columns.Add("col0");
dt.Columns.Add("col1");
dt.Columns.Add("col2");
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DataRow dr = dt.NewRow();
dr["col0"] = rdr["col0"];
dr["col1"] = rdr["col1"];
dr["col2"] = rdr["col2"];
dt.Rows.Add(dr);
}
con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
Did you get any exception? Try moving con.Close() after DataBind() and see how it goes.
Try to use the code below:
DataSet dataSet = new DataSet("newexample");
SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from newexample", connectionString);
dataAdapter.Fill(dataSet);
if (dataSet != null)
{
if (dataSet.Tables[0].Rows.Count != 0)
{
GridView1.DataSource = dataSet ;
GridView1.DataBind();
}
else
{
GridView1.DataSource = null;
GridView1.DataBind();
}
}
This is a better approach since SqlDataAdapter will take care for SqlConnection. It is responsible to create the connection and to close it at the end of operation in the best way possible.
This is not a tested code so if you have any problem let me know..
well, I've done everything on my behalf just to solve this problem. i'm trying to print the data from my database using grid view in asp.net using c# codes. can anyone tell me whats wrong and how to improve my codes. thank you.
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
{
constructor var = new constructor();
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader1 = cmd.ExecuteReader();
reader1.Close();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
You must fill the DataSet with data like this :
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "TableName");
GridView1.DataSource = ds.Tables["TableName"];
GridView1.DataBind();
You're assigning an empty DataSet to your DataSource, without filling the results of your DataReader into the DataSet/DataTable.
using (MySqlConnection con = new MySqlConnection(""))
{
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
try
{
DataTable dt = new DataTable();
using (MySqlDataReader reader1 = cmd.ExecuteReader())
{
dt.Load(reader1);
}
GridView1.DataSource = dt ;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
}
I am trying to populate a dropdownlist from sql server by using classes as shown below. The code breaks down when it comes to bind the data into the dropdown list. It gives an error on giving the dropdownlist the dataValueField and datatTextField.
HTML... a.aspx
<asp:DropDownList ID="NationalityDropDownList" runat="server" >
</asp:DropDownList>
C#... a.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Classes.Nationality PossibleNationality = new Classes.Nationality();
if (!Page.IsPostBack)
{
DataTable dataTable = PossibleNationality.getNationality();
NationalityDropDownList.DataSource = dataTable;
NationalityDropDownList.DataValueField = "ID";
NationalityDropDownList.DataTextField = "Nationality";
NationalityDropDownList.DataBind();
}
}
Nationality.cs
public class Nationality
{
public DataTable getNationality()
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["InformationConnection"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spGetAllUsers", conn);
comm.CommandType = CommandType.StoredProcedure;
DataTable dataTable;
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
dataTable = new DataTable();
da.Fill(dataTable);
}
finally
{
conn.Close();
}
return dataTable;
}
}
SQL procedure....
ALTER PROCEDURE [dbo].[spGetNationalities]
AS
BEGIN
select * from Nationality;
END
This line of code in your getNationalitymethod...
comm = new SqlCommand("spGetAllUsers", conn);
...should be this instead
comm = new SqlCommand("spGetNationalities", conn);
Databinding should work if your Nationality table has columns ID and Nationality
if (!Page.IsPostBack)
{
try
{
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}
}
catch (Exception Ex)
{
Console.WriteLine("Error: " + Ex.Message);
}
GetData();
}
I want to show my cart details on a Button_Click_Event. I'm using a Gridview control of ASP.NET framework. But the following exception occurs:
object reference is not set to a instance of an object.
How can I fix it? Here is my code:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
string st = "select * FROM cart_master";
cmd = new SqlCommand(st, sqlcon);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView GridView1 = (GridView)ContentPlaceHolder1.FindControl("GridView1");
sda.Fill(ds, "cart_master");
GridView1.DataSource = ds.Tables["cart_master"];
GridView1.DataBind();
cmd.Connection.Close();
}
Rather than dataset, just fill a datatable from your adapter
DataTable dataTable = new DataTable("ResultDataTable");
sda.Fill( dataTable);
GridView1.DataSource = dataTable;
How do I load data into combobox from database? I want to display the supportID into the combobox in the form. the code I am using is pasted here. I am calling BindData() in the formload. Ia m getting exception as: Cannot bind to the new display member.
Parameter name: newDisplayMember. the code I used is:
public void BindData()
{
SqlConnection con = new SqlConnection(#"server=RSTT2; database = Project ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select supportID from Support";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cbSupportID.DataSource = ds;
cbSupportID.DisplayMember = "supportID";
cbSupportID.ValueMember = "supportID";
cbSupportID.Enabled = true;
cmd.ExecuteNonQuery();
con.Close();
}
The DataSource for your combobox should be a DataTable in this case, try this:
cbSupportID.DataSource = ds.Tables[0];
Or better, you should fill data into a DataTable instead of a DataSet like this:
DataTable dt = new DataTable();
da.Fill(dt);
//...
cbSupportID.DataSource = dt;
public void BindData()
{
SqlConnection con = new SqlConnection(#"server=RSTT2; database = Project ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select supportID from Support";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
cbSupportID.DisplayMember = "supportID";
cbSupportID.ValueMember = "supportID";
cbSupportID.DataSource = ds;
cbSupportID.Enabled = true;
}
I hope this helps.
Follow this example:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace ComboBoxData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string conStr = #"Server =.\SQLEXPRESS2014; Database=NORTHWND; User Id=sa; Password=******";
SqlConnection conn = new SqlConnection(conStr);
DataSet ds = new DataSet();
string getEmpSQL = "SELECT E.LastName FROM dbo.Employees E;";
SqlDataAdapter sda = new SqlDataAdapter(getEmpSQL, conn);
try
{
conn.Open();
sda.Fill(ds);
}catch(SqlException se)
{
MessageBox.Show("An error occured while connecting to database" + se.ToString());
}
finally
{
conn.Close();
}
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = ds.Tables[0].Columns[0].ToString();
}
}
}
CmbDefaultPrinter.DisplayMember = "[table fieldname]";
CmbDefaultPrinter.ValueMember = "[table fieldname]";
CmbDefaultPrinter.DataSource = ds.Tables[0];
CmbDefaultPrinter.Enabled = true;
Mention the Column Name in DataField which you want to load.
and in aspx.cs in page load bind the gridview.
enter code here
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="User_Group" HeaderText="UserName" ItemStyle
Width="150px" />