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();
}
Related
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();
I am trying to insert data from my radGrid that has some data to my sql. in my rad grid i also have a check box column so i want the checked rows to be inserted in my db. i am using the code below but gives me this error:
Error 30 'Telerik.Web.UI.RadGrid' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'Telerik.Web.UI.RadGrid' could be found (are you missing a using directive or an assembly reference?) any idea where i am doing wrong???
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [ReportId], [Report], [IsSelected] FROM Hobbies"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
RadGrid1.DataSource = dt;
RadGrid1.DataBind();
}
}
}
}
}
protected void Rows()
{
}
protected void Save2_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Rights"].ConnectionString);
string insert = "insert into Rights(Name,Mbiemri,Gjinia,Departamenti,Mosha,IntRights,Transferta,Depozita,Rapore) values (#Name,#Mbiemri,#Gjinia,#Departamenti,#Mosha,#IntRights,#Transferta,#Depozita,#Rapore)";
SqlCommand cnd = new SqlCommand(insert, con);
con.Open();
foreach (GridViewRow row in RadGrid1.Rows)
{
//Get the HobbyId from the DataKey property.
int ReportID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
//Get the checked value of the CheckBox.
bool isSelected = (row.FindControl("chkSelect") as CheckBox).Checked;
//Save to database
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#ReportId", ReportID);
cmd.Parameters.AddWithValue("#IsSelected", isSelected);
cmd.ExecuteNonQuery();
}
cnd.Parameters.AddWithValue("#Name", TextBox1.Text);
cnd.Parameters.AddWithValue("#Mbiemri", TextBox2.Text);
cnd.Parameters.AddWithValue("#Gjinia", RadioButtonList1.SelectedValue);
cnd.Parameters.AddWithValue("#Departamenti", SelectDepartament.SelectedItem.Text);
cnd.Parameters.AddWithValue("#Mosha", RadDropDownList1.SelectedItem.Text);
cnd.Parameters.AddWithValue("#IntRights", RadDropDownList2.SelectedItem.Text);
cnd.Parameters.AddWithValue("#Transferta", TransfertaBtn.SelectedValue);
cnd.Parameters.AddWithValue("#Depozita", DepoziteBtn.SelectedValue);
cnd.ExecuteNonQuery();
Response.Redirect("Home.aspx");
con.Close();
}
catch (Exception ex)
{
}
telerik:RadGrid ID="RadGrid1"
runat="server" AllowMultiRowSelection="True" AllowPaging="True" DataSourceID="SqlDataSource1" GridLines="Both" PageSize="5" >
<GroupingSettings CollapseAllTooltip="Collapse all groups" />
<ClientSettings>
<Selecting AllowRowSelect="True" />
</ClientSettings>
<MasterTableView>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Report" HeaderText="Report" ItemStyle-Width="150px" />
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks2014ConnectionString %>" SelectCommand="SELECT [ReportID], [Report] FROM [Report]"></asp:SqlDataSource>
<br />
To access the rows, loop through its DataItems. More about Accessing Cells and Rows
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridDataItem row in RadGrid1.Items)
{
string rowValue = row["ColumnUniqueName"].Text;
}
}
Better approach would be to create a method that takes few parameters to Update the SQL database. Once done, call it inside the ItemDataBound event of RadGrid (Differences Between ItemCreated and ItemDataBound). In this event you can access the row, its cells, get the necessary value and update the database row-by-row.
bool IsClicked = false;
protected void Button1_Click(object sender, EventArgs e)
{
IsClicked = true;
RadGrid1.Rebind();
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (IsClicked && e.Item is GridDataItem)
{
updateDatabase(((GridDataItem)e.Item)["ColumnUniqueName"].Text);
}
}
protected void updateDatabase(string field)
{
// update SQL
}
i need to create a webpage containing a grid view with combo box. condition is:- the combo box value should be inserted on my SQL db and update the db/grid view when i click save button.[i added the image of proposed design of the page]any help with the code is so much appreciated! thank you!
GridView Markup
Below I have a simple GridView ASP.Net GridView control populated from the Customers table of Northwind database. It displays 2 columns Contact Name and City of which city is editable via ASP.Net DropDownList control. The identifier column Customer Id is bind to the DataKeyNames property.
<asp:GridView ID="gvCustomers" DataKeyNames = "CustomerId" runat="server" AutoGenerateColumns = "false" OnRowEditing = "EditCustomer" OnRowDataBound = "RowDataBound" OnRowUpdating = "UpdateCustomer" OnRowCancelingEdit = "CancelEdit">
<Columns>
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
<asp:TemplateField HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' Visible = "false"></asp:Label>
<asp:DropDownList ID = "ddlCities" runat = "server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Binding the GridView
Below is the code to Bind the GridView control with data.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
Editing the GridView Row
The below events handle the GridView Row Edit and Cancel Edit Events
C#
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}
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>
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.