I have gridview and some textbox that user can search .
when user search I updated gridview but when changed pageing I bind gridview again and I lost search result .
how can I change gridview paging without call DataBind Again?
I used this for Paging:
protected void grv_Data_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Data.PageIndex = e.NewPageIndex;
TicketDataBinding();
}
and my search method is :
protected void btn_search_Click(object sender, EventArgs e){
using (var ticket = new BLL.Ticket())
{
grv_Data.DataSource = tit.SelectList( fromDate, toDate);
grv_Data.DataBind();
}}
sorry I forgot asp.net webform and I dont know how do this ?
I've included two examples of binding data to a GridView where paging still works on filtered data. I hope it helps you.
1.You can do this completely in .ASPX:
<form id="form1" runat="server">
<asp:TextBox ID="txtEmailAddress" runat="server"></asp:TextBox>
<asp:Button runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" DataSourceID="sqlDS" AllowPaging="true" PageSize="5" AutoGenerateColumns="true">
<Columns>
<asp:BoundField DataField="EmailType" />
<asp:BoundField DataField="EmailAddress" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqlDS"
runat="server"
ConnectionString="<%$ ConnectionStrings:conn %>"
SelectCommand="SELECT EmailType, EmailAddress FROM EmailNotifications WHERE EmailAddress LIKE #EmailAddressParam + '%'">
<SelectParameters>
<asp:ControlParameter ControlID="txtEmailAddress" DbType="String" Name="EmailAddressParam" DefaultValue="%" />
</SelectParameters>
</asp:SqlDataSource>
</form>
2.Or in code behind:
public partial class PagingAndSearchingInGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.GetData();
}
private void GetData()
{
string emailAddress = txtEmailAddress.Text;
DataTable table = !Page.IsPostBack ? GetEmails() : GetEmails(emailAddress);
GridView1.DataSource = table;
GridView1.DataBind();
}
private DataTable GetEmails(string emailAddress = "%")
{
var table = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("SELECT EmailType, EmailAddress FROM EmailNotifications WHERE EmailAddress LIKE #EmailAddressParam + '%'", connection))
{
command.Parameters.AddWithValue("#EmailAddressParam", emailAddress);
using (var a = new SqlDataAdapter(command))
{
connection.Open();
a.Fill(table);
connection.Close();
}
}
}
return table;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.GetData();
}
}
While the pageIndex changed event, you can check whether the search button is already clicked or not. When clicking the search button you can set a hiddenfield value to 1 or something like that.
protected void grv_Data_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Data.PageIndex = e.NewPageIndex;
if(status==1) //Search button is already clicked, means the grid contains searched result
{
grv_Data.DataSource = tit.SelectList( fromDate, toDate);
}
else
{
//Search button is not clicked .. means the grid contains all records.
TicketDataBinding();
}
}
Related
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();
}
in my asp gird asp grid paging is not working what is the problem is my code please help me.. problem is when i click the paging items page is not post back..
here is my aspx code:
<asp:GridView ID="GridView1" Font-Size = "11pt" OnRowCommand="GridView1_RowCommand" AllowPaging="true" AllowSorting="true" PagerSettings-Visible="true" PageSize="4" CssClass="footable" runat="server" AutoGenerateColumns="false"
Style="max-width: 500px" DataKeyNames="Id" EnableViewState="true" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:ButtonField CommandName="Edit" ButtonType="Image" ImageUrl="~/image/redit.png" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="ProductDescription" HeaderText="Description" />
<asp:TemplateField>
<ItemTemplate>
<img src='data:image/jpg;base64,<%# Eval("ProductImage") != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval("ProductImage")) : string.Empty %>' alt="image" height="80" width="80" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="Delete" ButtonType="Image" ImageUrl="~/image/rdelete.png" />
</Columns>
<PagerStyle HorizontalAlign = "Right" />
</asp:GridView>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-footable/0.1.0/css/footable.min.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-footable/0.1.0/js/footable.min.js"></script>
<script type="text/javascript">
$(function () {
$('[id*=GridView1]').footable();
});
</script>
and here is my aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
LoadGrid();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.GridView1.DataKeys[rowIndex]["Id"];
if (e.CommandName == "Edit")
{
}
else if (e.CommandName == "Delete")
{
}
}
public void LoadGrid()
{
try
{
BusinessLogic.clsGeneral objGen = new BusinessLogic.clsGeneral();
string strquery = "select * from Products where status = 1";
DataTable dt = objGen.ExecuteQueryReturnDatatable(strquery);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
catch (Exception)
{
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
try like this:
You need to Bind Your GridView Again in PageIndexChanging event
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
LoadGrid();
}
Add datasource agin to your paging,
Try replacing the below snippet from yours.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BusinessLogic.clsGeneral objGen = new BusinessLogic.clsGeneral();
string strquery = "select * from Products where status = 1";
DataTable dt = objGen.ExecuteQueryReturnDatatable(strquery);
GridView1.DataSource = dt;
GridView1.DataBind();
}
some points still here to be mentioned
Avoid inLine queries, that doesn't seems good
inspite calling data all over again to bind, you can use some other trick as well.
And in Sql ,never return *(all) , return only sets of column you need, * is not good practice.
Eg. select name,address,phone from .... instead of select *...
BundleTable.EnableOptimizations = false;
bundles.Add(new ScriptBundle("~/Scripts/jquery").Include(
"~/Scripts/jquery-1.11.2.min.js",
"~/Scripts/jquery.ui.min.js"
));
bundles.Add(new ScriptBundle("~/Scripts/customscripts").Include(
"~/Scripts/BeatPicker.min.js",
"~/Scripts/chosen.jquery.js",
"~/Scripts/legacy.js",
"~/Scripts/custombox.js",
"~/Scripts/ion.rangeSlider.js",
"~/Scripts/ion.rangeSlider.min.js",
"~/Scripts/iCheck/icheck.min.js",
// "~/Scripts/jquery.ui.datepicker1.min.js",
"~/Scripts/jquery.dataTables.min.js",
"~/Scripts/jquery.ui.datepicker.monthyearpicker.js",
"~/Scripts/jquery.unobtrusive-ajax.min.js",
"~/Scripts/jquery.akordeon.js",
"~/Scripts/jquery.autogrow-min.js",
"~/Scripts/jquery.corner.js",
I have created a datatable globaly and i have add columns to it in the page load event.
Now i want to add data to it in a button click event..
When I do it as below I get a error saying....
Column 'catID' does not belong to table
What is the solution... Do i need to use sessions... ? the code is like below
public partial class Default2 : System.Web.UI.Page
{
DataTable dtSelectedSeats = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dtSelectedSeats.Columns.Add("catID", typeof(string));
dtSelectedSeats.Columns.Add("seatID", typeof(string));
}
}
protected void seat_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (button.BackColor == Color.Cyan)
{
button.BackColor = Color.Lime;
addSeat(button.Text);
}
}
private void addSeat(string seatNo)
{
DataRow dr;
dr = dtSelectedSeats.NewRow();
dr["catID"] = ddlCategory.SelectedItem.Value.ToString();
dr["seatID"] = seatNo;
dtSelectedSeats.Rows.Add(dr);
}
}
ASPX:
<asp:DropDownList ID="ddlCategory" runat="server">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
<asp:ListItem>c</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="seat" runat="server" BackColor="Cyan" onclick="seat_Click" Text="1" />
<asp:Button ID="Button1" runat="server" BackColor="Cyan" onclick="Button1_Click" Text="2" />
<asp:Button ID="Button2" runat="server" BackColor="Cyan" onclick="Button2_Click" Text="3" /><br />
<asp:GridView ID="GridView1" runat="server"/>
Code behind:
protected void seat_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (button.BackColor == Color.Cyan)
{
button.BackColor = Color.Lime;
addSeat(button.Text);
}
}
private void addSeat(string seatNo)
{
if (Session["dt"] == null)
{
Response.Write("DataTable not exist!");
return;
}
DataTable dtSelectedSeats = (DataTable)Session["dt"];
DataRow dr = dtSelectedSeats.NewRow();
dr["catID"] = ddlCategory.SelectedItem.Value.ToString();
dr["seatID"] = seatNo;
dtSelectedSeats.Rows.Add(dr);
GridView1.DataSource = dtSelectedSeats;
GridView1.DataBind();
Session["dt"] = dtSelectedSeats;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtSelectedSeats = new DataTable();
dtSelectedSeats.Columns.Add("catID", typeof(string));
dtSelectedSeats.Columns.Add("seatID", typeof(string));
Session["dt"] = dtSelectedSeats;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
seat_Click(sender, e);
}
protected void Button2_Click(object sender, EventArgs e)
{
seat_Click(sender, e);
}
just remove the if (!IsPostBack)
coz when you click the button , the page will post back.
Your Code is perfectly correct for DataTable, the error you are getting may be for some different problem. Please specify correctly your error
Just off the top of my head it looks as if you are adding the rows in the wrong event. I'm not sure your DataTable has been initialized at the point you are adding columns to it (thus throwing away your changes). Try putting your PageLoad code into PagePrerender and see if that gives you a better result.
This seems like a repeated question but i'm not able to get my answer.
I have a grid view and I need to delete a particular row, when I click on a button outside the gridview.
protected void btnDelete_Click(object sender, EventArgs e)
{
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[DataGV1.SelectedIndex];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
The session variable has the previous state of datatable.
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
_selectedIndex = int.Parse(e.CommandArgument.ToString());
}
Gridview controls
onselectedindexchanged="DataGV1_SelectedIndexChanged"
OnRowCommand="DataGV1_RowCommand" OnRowDeleting="DataGV1_RowDeleting"
AutoGenerateSelectButton="False" DataKeyNames="Role,Last_name">
<Columns>
<asp:ButtonField DataTextField="last_name" HeaderText="Last_name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="role" HeaderText="role" SortExpression="role" />
<asp:BoundField DataField="role" HeaderText="role" HeaderText="Frist_name"
SortExpression="first_name" Text="First_name" />
</Columns>
</asp:GridView>
This doesn't seem to work.
Can u please tell me where I am going wrong?
If button is outside the GridView then no need to handle RowCommand event (In fact it is inappropriate).
Suggestion:
You have to add a TemplateField column, drop the CheckBox control in ItemTemplate of TemplateField and write code in click handler of button to traverse the GridView.Rows collection, identify the selected row by reading value of CheckBox control and perform deletion action if that CheckBox is checked.
Demo DataSource (List<T>)
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public static List<Item> Data()
{
List<Item> list = new List<Item>()
{
new Item(){ ID=11, Name="A"},
new Item(){ ID=12, Name="B"},
new Item(){ ID=13, Name="C"},
new Item(){ ID=14, Name="D"},
new Item(){ ID=15, Name="E"},
};
return list;
}
}
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Button" />
Code-behind (Page_Load)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["data"] = Item.Data();
GridView1.DataSource = Session["data"];
GridView1.DataBind();
}
/*--- RowCommand handler ---*/
GridView1.RowCommand += (sa, ea) =>
{
ViewState["RowIndex"] = ea.CommandArgument.ToString();
};
/*--- Delete button click handler ---*/
btnDelete.Click += (sa, ea) =>
{
if (ViewState["RowIndex"] != null)
{
int index = int.Parse(ViewState["RowIndex"].ToString());
List<Item> items = Session["data"] as List<Item>;
items.RemoveAt(index);
GridView1.DataSource = Session["data"];
GridView1.DataBind();
ViewState["RowIndex"] = null;
}
};
}
You have to store the _selectedIndex in a ViewState, and then on delete button click you retrieve the _selectedIndex from the Viewstate and use that to delete the row from your dataset, and reload the grid.
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
ViewState["SelIndex"] = e.CommandArgument.ToString();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if(ViewState["SelIndex"] == null)
return;
int selIndex = int.Parse(ViewState["SelIndex"]);
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[selIndex ];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
take a look at these articles that would explain to delete a single/multiple rows from gridview.
http://technico.qnownow.com/2012/06/15/how-to-delete-multiple-rows-from-gridview-with-checkboxes/
http://technico.qnownow.com/2012/06/14/how-to-delete-a-row-from-gridview-with-client-side-confirmation/