Gridview is not populating using databind - c#

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.

Related

when try to add check box to grid view on asp.net forms i get error?

I work on asp.net web forms with c# I need to add checkbox column as last column on gridview
but i don't know how to add it
static string con =
"Data Source=DESKTOP-L558MLK\\AHMEDSALAHSQL;" +
"Initial Catalog=UnionCoop;" +
"User id=sa;" +
"Password=321;";
SqlConnection conn = new SqlConnection(con);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewSearch.DataSource = GetDataForSearch();
GridViewSearch.DataBind();
}
}
public DataTable GetDataForSearch()
{
string response = string.Empty;
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select top 10 datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, id from Print_Report";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 50000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
catch (Exception ex)
{
response = ex.Message;
}
finally
{
cmd.Dispose();
conn.Close();
}
return dt;
}
on aspx page
<asp:GridView ID="GridViewSearch" runat="server">
</asp:GridView>
GridViewSearch.DataSource = GetDataForSearch();
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
GridViewSearch.Columns.Add(checkColumn);
GridViewSearch.DataBind();
I get error on line below
GridViewSearch.Columns.Add(checkColumn);
argument 1 can't convert from system.windows.forms.datagridviewcheckbox to system.web.ui.webcontrol.databoundfield
so how to solve this issue please ?
Seems to me, that if you want say a button, or check box, or dropdown?
why not just add it to the markup.
So, say like this:
<div id="MyGridPick" runat="server" style="display:normal;width:40%">
<asp:Label ID="lblSel" runat="server" Text="" Font-Size="X-Large"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" cssclass="table table-hover" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="120px" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Then my code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
Now, of course I get VERY tired of typing that connection string stuff over and over. So, I have a "genreal" routine like this:
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the result of running above:
So, kind of hard to make the case to "add" a check box control, when you can just drop one into the gridview.
Same goes for a button, maybe we want a button to "view" or edit the above row, or some such.
So, once again, just drop in a plain jane button, say like this:
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="bView" runat="server" Text="View" CssClass="btn"
OnClick="bView_Click" />
</ItemTemplate>
</asp:TemplateField>
And now we have this:
And EVEN better?
Well, since that button (or check box) is a plain jane standard control?
then you can add standard events, like a click event, or whatever you want.
Say this code for the button click (shows how to get current row).
protected void bView_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
DataTable dtHotel = MyRstP(cmdSQL);
General.FLoader(MyEditArea, dtHotel.Rows[0]);
MyGridPick.Style.Add("display", "none"); // hide grid
MyEditArea.Style.Add("display", "normal"); // show edit div area
}
And we now get/see this:
Edit: Process each checked/selected row.
this:
protected void cmdSelProcess_Click(object sender, EventArgs e)
{
// process all rows in GV with check box
String sPK = "";
List<int> MySelected = new List<int>();
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gRow.FindControl("chkSel");
if (chkSel.Checked)
{
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
// add pk value of row to our list
MySelected.Add(PK);
// Or we could process data based on current gRow
if (sPK != "")
sPK += ",";
sPK += PK.ToString();
Debug.Print(PK.ToString());
}
}
// at this point, we have a nice list of selected in MySelected
// or, maybe process as a data table
SqlCommand cmdSQL =
new SqlCommand($"SELECT * FROM tblHotelsA where ID IN({sPK})");
DataTable rstSelected = MyRstP(cmdSQL);
//
foreach (DataRow dr in rstSelected.Rows)
{
// do whatever
}
}
Datagridviewcheckboxcolumn is a Windows formx object. You are working in web forms. Please see the link below for information on the webforms check box field
CheckBoxField checkColumn = new CheckBoxField();

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();
}

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

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

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>

Categories