Retrieve result of search data from SQL server database to gridview [duplicate] - c#

How to bind a GridView?
I want to display my table data in a gridview.
I have createed SQL table EmpDetail with columns ID, Name, Salary Data

Try below code according to your scenario
I hope it helps you
protected void GridviewBind ()
{
using (SqlConnection con = new SqlConnection("Data Source=RapidProgramming;Integrated Security=true;Initial Catalog=RPDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
}
}
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#3366CC" BorderStyle="None"
BorderWidth="1px" CellPadding="4"
style="text-align: center; margin-left: 409px" Width="350px">
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>;

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
bindData();
}
}
public void bindData() {
SqlConnection con=new SqlCponnection(ConnectionStrings);
SqlDataAdapter da = new SqlDataAdapter("select * from Your TableName", con);
DataSet ds = new DataSet();
try {
da.Fill(ds, "YourTableName");
GridView1.DataSource = ds;
GridView1.DataBind();
} catch (Exception e) {
Response.Write( e.Message);
} finally {
ds.Dispose();
da.Dispose();
con.Dispose();
}

In order to run this code, you need to replace connectionstring's credentials myServerName\myInstanceName, myDataBase, myUsername, myPassword with yours
using System.Data;
using System.Data.SqlClient;
string sConnectionString = #"Data Source=myServerName\myInstanceName;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;";
protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack)
BindGridView();
}
private void BindGridView() {
DataTable dt = new DataTable();
SqlConnection con = null;
try {
string sQuery = "SELECT ID, Name, Salary FROM EmpDetail";
SqlConnection con = new SqlConnection(sConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(sQuery, con);
SqlDataReader sdr = cmd.ExecuteReader();
dt.Load(sdr);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
catch{ }
finally{
dt.Dispose();
con.Close();
}
}

try this....
protected void Page_Load(object sender, EventArgs e)
{
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("select * from Table1", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
conn.Close();
}
}
<div>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>

You could simply use the SqlDataSource. You would move the SqlDataSource from the toolbox where it says Data, SqlDataSource. You would then configure the datasource using the smart tag. Then using the smart tag on the gridview, select the SqlDataSource you placed onto the aspx page. This is really quick and requires little to no coding. http://msdn.microsoft.com/En-us/Library/z72eefad.aspx this will show you a little bit more. Hope this helps you!

use Class7917
select * from Emp
alter table Emp add images varchar(100)
sp_helptext 'usp_emp_insert_update'
alter proc usp_emp_insert_update
#empid int,
#name varchar(50),
#cid int,
#sid int,
#dob datetime,
#isactive int,
#hobbies varchar(100),
#images varchar(100)
as
begin
if(#empid=0)
begin
insert into Emp(Name,cid,sid,dob,isactive,hobbies,images)
values(#Name,#cid,#sid,#dob,#isactive,#hobbies,#images)
end
else
begin
update Emp set Name=#name,cid=#cid,sid=#sid,
dob=#dob,isactive=#isactive,hobbies=#hobbies,images=#images
where EmpID=#empid
end
end
truncate table Emp

Related

How to manage Large amount of Data in GridView

I Have a table with 10000 records, so I want call only 15 Records at a single time using Stored procedure.
At the Next time call only next 15 Reocords and go On...
Please Help me out!!...If Possible Give Code With Example and Stored Procedure...Thank You!!!
Use paging in gridview as AllowPaging="true" then use
OnPageIndexChanging Event and give us PageSize see below example
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="Column_Name" HeaderText="Header Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="Column_Name" HeaderText="Header Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="Column_Name" HeaderText="Header Name" />
</Columns>
</asp:GridView>
Now bind the gridview with database on Page_Load Event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
string conStr = #"Your connection string here";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Table_Name"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
for pages use newPageIndex on OnPageIndexChanging event
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}

asp.net generate Gridview by DropDownList IndexChange

I'm trying to generate a GridView and fill it by DropDownList SelectedValue
I have a DropDownList bind to Country data table and GridView bind to State data table and by changing the value of the DropDownList the data in the GridView change too
i'v tried this code:
this to fill the dropdownlist:
protected void FillDropdownList()
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter();
DataTable dt = new DataTable();
try
{
cmd = new SqlCommand("Select * from Country", con);
adp.SelectCommand = cmd;
adp.Fill(dt);
DropDownListCountry.DataSource = dt;
DropDownListCountry.DataTextField = "CountryName";
DropDownListCountry.DataValueField = "CountryID";
DropDownListCountry.DataBind();
//DropDownListCountry.Items.Insert(0, "-- Select --");
//OR ddlEmpRecord.Items.Insert(0, new ListItem("Select Emp Id", "-1"));
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
}
finally
{
cmd.Dispose();
adp.Dispose();
dt.Clear();
dt.Dispose();
}
}
and this to generate the gridView
protected void BindGrid()
{
con.Open();
SqlCommand com = new SqlCommand("select * from State where CountryID='" + DropDownListCountry.SelectedValue + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
and finally that's where i'm calling the functions:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
FillDropdownList();
}
}
protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
{
BindGrid();
}
the .aspx file:
<asp:DropDownList ID="DropDownListCountry" runat="server" DataTextField="CountryName" DataValueField="CountryID" OnSelectedIndexChanged="DropDownListCountry_SelectedIndexChanged" >
</asp:DropDownList>
<br />
<!-- SqldataSource and GridView and Formview for State -->
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="State Id" DataField="StateID" />
<asp:BoundField HeaderText="State Name" DataField="StateName" />
<asp:BoundField HeaderText="Country Id" DataField="CountryID" />
</Columns>
</asp:GridView>
but the code is not working and when i'm changing the value of DropDownList the GridView is not changing
For your Dropdownlist set AutoPostBack = true

Gridview didn't display on page load in c#

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = Connection.DBconnection();
{
SqlCommand com = new SqlCommand("sp_selectlendingstatus", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#studentid", txtstudentid.Text.Trim());
com.Parameters.AddWithValue("#bookid", txtbookid.Text.Trim());
com.Parameters.AddWithValue("#status", status.Text.Trim());
SqlDataAdapter sda = new SqlDataAdapter(com);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" EnablePersistedSelection="True" BackColor="White"
Height="240px"
Width="755px">
<Columns>
<asp:BoundField DataField="ID" HeaderText="Student_Id" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Book_id" HeaderText="Book_id" InsertVisible="False" ReadOnly="True" SortExpression="Book_id" />
<asp:BoundField DataField="Book_name" HeaderText="Book_name" SortExpression="Book_name" />
<asp:BoundField DataField="Author_name" HeaderText="Author_name" SortExpression="Author_name" />
<asp:BoundField DataField="Publisher_name" HeaderText="Publish_name" SortExpression="Publisher_name" />
<asp:BoundField DataField="Publish_date" HeaderText="Publish_date" SortExpression="Publish_date" />
<asp:BoundField DataField="status" HeaderText="Status" SortExpression="status" />
</Columns>
</asp:GridView>
sp:
ALTER PROCEDURE sp_selectlendingstatus
AS
Begin
select * from book_lending left outer join studentlibrary ON studentlibrary.Book_id=book_lending.bookid
End
I'm new to .net..
In page load, i need o display gridview.
I tried above source code, but when i run gridview didn't show.
It shows error, sp_selectlendingstatus has no parameters passed.
So if i add parameters in sp_selectlendingstatus procedure like this,
ALTER PROCEDURE sp_selectlendingstatus
(
#bookid int,
#studentid int,
#status varchar(50)
)
AS
Begin
select * from book_lending left outer join studentlibrary ON studentlibrary.Book_id=book_lending.bookid
End
and run EXEC sp_selectlendingstatus in sql server.
It shows error #studentid, #bookid which was not supplied.
May i know what is mistake in my code?
Any help would be highly appreciated.
Thanks,
Based on your select query you can write like the following format.Before binding the grid you must check all retrieve columns name are present in the gridview otherwise it throw errors.
private void BindStudents()
{
String strConnStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
SqlConnection con = new SqlConnection(strConnStr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_selectlendingstatus";
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
GridView1.DataSource = cmd.ExecuteReader() ;
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}

Error: The type specified in the TypeName property of ObjectDataSource could not be found

I've got a Datatable with a Sql Connection and am trying to bind that to a GridView, however I get the error that the type specified in the TypeName property could not be found.
My datatable code looks like this :
protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (!IsPostBack)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "TestConnectionString";
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "SELECT* FROM TestTable";
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
GridView1.DataSource = data;
}
and the code in the .aspx :
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" >
<Columns>
<asp:BoundField DataField="Column1" HeaderText="Column1" ReadOnly="True" SortExpression="Column1" >
<HeaderStyle Width="450px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Column2" HeaderText="Column2" ReadOnly="True" SortExpression="Column2" >
<ItemStyle Width="400px" HorizontalAlign="Center" />
</asp:BoundField>
</Column>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="DataTable" TypeName="data"></asp:ObjectDataSource>
Suggestions on what I've done wrong?
That's not how the ObjectDataSource control is meant to be used.
If you just want to bind the grid on the first page load, then remove the ObjectDataSource control, remove the ObjectDataSource1_Selecting event handler, remove the DataSourceID property from the GridView, and just bind the grid when the page loads:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
using (SqlConnection conn = new SqlConnection("your connection string here"))
using (SqlCommand command = new SqlCommand("SELECT * FROM TestTable", conn))
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
}
If you want to use the ObjectDataSource control, then give it a valid TypeName and SelectMethod, remove the ObjectDataSource1_Selecting event handler, and have the SelectMethod return the data:
public static class YourDataSource
{
public static DataTable LoadSomeData()
{
using (SqlConnection conn = new SqlConnection("your connection string here"))
using (SqlCommand command = new SqlCommand("SELECT * FROM TestTable", conn))
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
return data;
}
}
}
Markup:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="YourDataSource"
SelectMethod="LoadSomeData"
/>
If you're using .NET 4.5, you could also use "model binding" to load the data from the code-behind without using a data-source control:
public DataTable LoadSomeData()
{
using (SqlConnection conn = new SqlConnection("your connection string here"))
using (SqlCommand command = new SqlCommand("SELECT * FROM TestTable", conn))
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
return data;
}
}
Markup:
<asp:GridView ID="GridView1" runat="server"
AllowSorting="True"
AutoGenerateColumns="False"
SelectMethod="LoadSomeData"
>
<Columns>
...
</Columns>
</asp:GridView>

Gridview is not populating using databind

I have the following ASP gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="TEXT" HeaderText="TEXT" SortExpression="TEXT" />
<asp:BoundField DataField="session_id" HeaderText="session_id" SortExpression="session_id" />
<asp:BoundField DataField="status" HeaderText="status" SortExpression="status" />
<asp:BoundField DataField="command" HeaderText="command" SortExpression="command" />
<asp:BoundField DataField="cpu_time" HeaderText="cpu_time" SortExpression="cpu_time" />
<asp:BoundField DataField="total_elapsed_time" HeaderText="total_elapsed_time" SortExpression="total_elapsed_time" />
<asp:BoundField DataField="dbname" HeaderText="dbname" ReadOnly="True" SortExpression="dbname" />
<asp:BoundField DataField="user_running_query" HeaderText="user_running_query" SortExpression="user_running_query" />
</Columns>
</asp:GridView>
In the code behind I have:
protected void Page_Load(object sender, EventArgs e)
{
using (Repository.SqldbAllQueries())
{
GridView1.DataBind();
}
}
And my Repository class contains:
public static class Repository
{
public static SqlDataReader SqldbAllQueries()
{
SqlConnection sqlConnection1 = new SqlConnection("Data Source=sqldb;Initial Catalog=ReportServer;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = #"SELECT sqltext.TEXT,req.session_id,req.status,req.command,req.cpu_time,
req.total_elapsed_time,DB_NAME(req.database_id) as dbname,s.login_name as user_running_query
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
INNER JOIN sys.dm_exec_sessions s ON req.session_id = s.session_id";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
}
I am attempting to capture every currently running query on the sql databse and output in in my ASP page as a grid view using the databind method, the code builds and runs however the gridview does not present itself on the page. I have stepped through the code and I can see that reader contains rows, but I seem to missing something here as they are not being added to the gridview, can anyone see the problem?
try this one,
in pageload
GridView1.DataSource = Repository.SqldbAllQueries();
GridView1.DataBind();
Try this code. Actually if you return reader, you may get an exception.
protected void Page_Load(object sender, EventArgs e)
{
DBAccess db = new DBAccess();
db.FetchData(BindData);
}
private void BindData(SqlDataReader reader)
{
DataGridView1.DataSource = reader;
DataGridView1.DataBind();
}
And here the DBAccess class(which is similar to Repository class)
public void FetchData(Action<SqlDataReader> bindMethod)
{
using (SqlConnection sqlConnection = new SqlConnection("ConnectionString"))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("Query", sqlConnection))
{
bindMethod.Invoke(sqlCommand.ExecuteReader(CommandBehavior.CloseConnection));
}
}
}
Hope this code helps.

Categories