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();
}
}
Related
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();
}
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
Here is my aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1"
OnRowCommand="GridView1_RowCommand" AutoGenerateSelectButton="True" EnablePersistedSelection="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
<asp:BoundField DataField="Section" HeaderText="Section"
SortExpression="Section" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button runat="server" ID="btnedit" Text="Edit" CommandName="EditRow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Deleterow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is code behind:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
GridViewRow gr = GridView1.SelectedRow;
gr.Cells[1].Text = Textusername.Text;
gr.Cells[2].Text = Textclass.Text;
gr.Cells[3].Text = Textsection.Text;
gr.Cells[4].Text = Textaddress.Text;
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
The selected row did not select in gridview. May i know how to enable gridview row. I used msdn and other documents and i followed,but nothing helps.
I design i set enable selection, but still i didn't find out issue.
Can anyone help me?
Thanks,
Basically we get SelectedRow of GridView Upon some GridviewRow Action event like OnSelectedIndexChanged , OnSelectedIndexChanging , OnRowEditing or from Template control like Button click. But here in your coding I don't think your btnsub_Click is inside Gridview so If you want to use the SelectedGridViewRow after your GridviewRow Action event then save the index in some temporary variable or pass the variable to method as argument.
protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
int index = Gridview1.SelectedIndex;
hiddenfield.Value = index.ToString();
}
OR In OnRowEditing also you can get the index of row
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
int index = gr.RowIndex;
hidval.Value = index.ToString();
}
}
and on button Click you can get the hiddenfield value as index:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
if(!String.IsNullOrEmpty(hiddenfield.Value))
{
int index = Convert.ToInt16(hiddenfield.Value);
GridView1.Rows[index].Cells[1].Text = Textusername.Text;
GridView1.Rows[index].Cells[2].Text = Textclass.Text;
GridView1.Rows[index].Cells[3].Text = Textsection.Text;
GridView1.Rows[index].Cells[4].Text = Textaddress.Text;
}
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
I have a DataGridView on a page. When I call that page whole list comes. I have decided to add pagination to the GridView.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_Del" OnSelectedIndexChanging="GridView1_Sel" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" SortExpression="id" Visible="false" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="author" HeaderText="Author" SortExpression="author" />
<asp:BoundField DataField="active" HeaderText="Active" SortExpression="active" />
<asp:CommandField HeaderText="Delete" SelectText="Delete" ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
//Page_Load()
gridFill();
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
gridFill() method fills the GridView.
public void gridFill()
{
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/inetpub/example.com/db/db.mdb");
sql = "SELECT id, name, author, active, FROM [table]";
dt = new DataTable();
try
{
if (conn.State != ConnectionState.Open) conn.Open();
comm= new OleDbCommand(sql, conn);
da= new OleDbDataAdapter(comm);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.OleDb.OleDbException ex)
{
string msg = "Error: ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
When I call the page it still gets all the rows at once. Also if I click 11th or later (because I limit the paging to 10 rows) rows for deleting I get index error.
So I have added another Button labeled as 'Refresh' which calls gridFill() method once more. Then pagination gets valid.
What could be the reason for GridView not paging for the first time?
If I change the order of the lines
//Page_Load()
gridFill();
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
to
//Page_Load()
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
gridFill();
it works. I can't believe it
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.