Sorting gridview column in asp.net - c#

I have a gridview that loads data from database. The data is displayed in the gridview for the first time sorted by datetime. On one column of that gridview I want to allow sorting, for example on the main_post column. I had tried this, but the gridview still did not sort when I click the header of the column.
This is my front-end code for gridview:
<asp:DataGrid ID="Datagrid1" runat="server"
AllowPaging="True"
AllowSorting="True"
OnSorting="ComponentGridView_Sorting">
<Columns>
<asp:BoundColumn DataField="main_post" HeaderText="Header Post ID"
SortExpression="ComponentGridView_Sorting" />
</Columns>
</asp:DataGrid>
My back-end code:
protected void loadData()
{
DataTable dtTemp;
dtTemp = objDBInterface.getResults(strSQL);
Datagrid1.DataSource = dtTemp;
Datagrid1.DataBind();
ViewState["dtbl"] = dtTemp;
}
protected void ComponentGridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = ViewState["dtbl"] as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);
Datagrid1.DataSource = dataView;
Datagrid1.DataBind();
}
}
private string ConvertSortDirection(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
I dont have any error and I dont know where my mistake is, could somebody please help me to solve this problem?
Thanks in advance.

Simple, set Allowsorting property true and add sorting event in your gridview.
<asp:GridView ID="GridView1" runat="server" AllowSorting="true"
OnSorting="GridView1_Sorting">
</asp:GridView>
Now add Event OnSorting in .cs file
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
SetSortDirection(SortDireaction);
if (dataTable != null)
{
dataTable.DefaultView.Sort = e.SortExpression + " " +_sortDirection;
GridView1.DataSource = dataTable;
GridView1.DataBind();
SortDireaction = _sortDirection;
}
}
protected void SetSortDirection(string sortDirection)
{
if (sortDirection == "ASC")
{
_sortDirection = "DESC";
}
else
{
_sortDirection = "ASC";
}
}

I got the solution. Hope this will help others people that face this similar problem. On .aspx page need to change:
from OnSorting="ComponentGridView_Sorting"
to onsortcommand="ComponentGridView_Sorting"
Then put this code on aspx.cs(back-end code):
protected void Datagrid1_SortCommand(object source, DataGridSortCommandEventArgs e)
{
string strSQL;
DataTable dt;
strSQL = "YOUR SELECT STATEMENT (SQL)";
dt = strSQL;
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
Datagrid1.DataSource = sortedView;
Datagrid1.DataBind();
}
}
protected SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}

Do not take tension developers it's really too easy follow my steps
Step 1 Create GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true" class="w3-table-all"
OnPageIndexChanging="OnPageIndexChanging" PageSize="20" >
<Columns>
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="250px" DataField="sn_no" HeaderText="ID" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="name" HeaderText="Name" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="mo" HeaderText="Mobile" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="email" HeaderText="Email Id" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="loc" HeaderText="Location" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="date" HeaderText="Date" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="day2" HeaderText="Day" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="date" HeaderText="Date" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="time" HeaderText="Time" />
</Columns>
</asp:GridView>
Step 2 Goto *.aspx.cs file and write
a). For descending order
cmd = new MySqlCommand("SELECT * FROM appointment ORDER BY sn_no DESC", con);
b). For ascending order
cmd = new MySqlCommand("SELECT * FROM appointment ORDER BY sn_no ASC", con);
Thanks with love #Vaibhav Yadav
Vaibhav Designs
http://vaibhavdesigns.org
for more ...

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="empid" DataSourceID="SqlDataSource1" EnableModelValidation="True" ForeColor="#333333" GridLines="None">

Related

How do I add multiple hyperlinks to a table cell from a list in the datasource?

I need to add multiple hyperlinks to the table cell in radgrid so users can click the link to redirect them to another page. The datasource of the grid is a domain which contains a list of links for each customer.
public class CustomerOverviewDomain
{
public CustomerEntity Entity { get; set; }
public IEnumerable<LeadDomain> Leads { get; set; }
public IEnumerable<QualifiedLeadsDomain> QualifiedLeads { get; set; }
public IEnumerable<ProspectDomain> Prospects { get; set; }
public List<string> Links
{
get
{
//NavigateUrl = '<%# "~/Reporting/SalesProposal/ProposalDownload.aspx?proposalId="+Eval("entity.ProposalId") %>' >
List<string> Links = new List<string>();
foreach (LeadDomain lead in Leads)
{
string link = "~/LeadsManagement/Leads/LeadsDetail.aspx?leadId=" + lead.entity.LeadId;
Links.Add(link);
}
foreach (QualifiedLeadsDomain qlead in QualifiedLeads)
{
string link = "!/LeadsManagement/QualifiedLeads/QualifiedLeadDetailPage.aspx?qualifiedLeadId=" + qlead.Entity.QualifiedLeadId;
}
foreach (ProspectDomain prospect in Prospects)
{
string link = "~/Prospects/ProspectDetailPage.aspx?prospectId=" + prospect.entity.ProspectMasterId;
Links.Add(link);
}
return Links;
}
}
}
I am unsure of what should be the column in the radgrid and how the data should be databound.
<%--<telerik:GridBoundColumn HeaderText="Links"
DataField="Links" SortExpression="Links" UniqueName="Links"
ShowFilterIcon="false" CurrentFilterFunction="Contains" AutoPostBackOnFilter="false" FilterDelay="500">
<HeaderStyle Width="120px" />
</telerik:GridBoundColumn>--%>
<telerik:GridHyperLinkColumn DataTextField="Links" DataNavigateUrlFields="Links" UniqueName="Links">
</telerik:GridHyperLinkColumn>
<%-- <telerik:GridTemplateColumn
UniqueName="Links"
AllowFiltering="false"
HeaderText="URL">
<ItemTemplate>
<asp:HyperLink ID="Link" runat="server"></asp:HyperLink>
</ItemTemplate>
</telerik:GridTemplateColumn>--%>
I'm guessing something has to be done in the databound event but not sure what exactly. I'm stuck here. Most I could get is a hyperlink "System.Collections.Generic.List`1[System.String]" which links nowhere. Could someone point me in the right direction?
protected void rgCustomer_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
//Get the row from the grid.
GridDataItem item = e.Item as GridDataItem;
if (item != null)
{
List<string> links = item["Links"].;
//GridTableCell linkCell = (GridTableCell)item["Links"];
//var Link = item["Links"];
//if (Link != null)
//{
// TableCell cell = item["Links"];
// if (cell != null)
// {
// }
//}
}
}
//// GridTableCell linkCell = (GridTableCell)item["TemplateLinkColumn"];
// HyperLink reportLink = (HyperLink)reportLinkCell.FindControl("Link");
// // Set the text to the quote number
// reportLink.Text = "Google";
// //Set the URL
// reportLink.NavigateUrl = "http://www.google.com";
// //Tell it to open in a new window
// reportLink.Target = "_new";
}
What you basically need is a nested Grid in a template column. The way i have dealt with this is to nest a radgrid in a template column and on the ItemDataBound event of the parent row, find the nested radGrid and the DataKeyName. I then use the datakey value to pull the data for the current row and bind the data to the nested RadGrid.
ASPX:
<telerik:RadGrid ID="RadGrid3" runat="server" OnNeedDataSource="RadGrid3_NeedDataSource" AutoGenerateColumns="false" OnItemDataBound="RadGrid3_ItemDataBound">
<MasterTableView DataKeyNames="ID">
<Columns>
<%-- Other columns --%>
<telerik:GridBoundColumn UniqueName="Id" DataField="ID" HeaderText="ID"></telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Name" DataField="Name" HeaderText="Name"></telerik:GridBoundColumn>
<%-- Column with nested template --%>
<telerik:GridTemplateColumn UniqueName="Links" HeaderText="Links">
<ItemTemplate>
<telerik:RadGrid ID="RadGrid4" runat="server" Skin="Windows7" RenderMode="Lightweight">
<MasterTableView DataKeyNames="Id" AutoGenerateColumns="False" ShowHeader="false">
<Columns>
<%-- I have included an id and name column for demo purposes. they can be removed so only the link is displayed --%>
<telerik:GridBoundColumn DataField="ID" ReadOnly="True" HeaderText="Id" SortExpression="Id" UniqueName="Id" DataType="System.Int32" FilterControlAltText="Filter Id column"></telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Name" ReadOnly="True" HeaderText="Name" SortExpression="Name" UniqueName="Name" DataType="System.Int32" FilterControlAltText="Filter Name column"></telerik:GridBoundColumn>
<telerik:GridHyperLinkColumn DataNavigateUrlFields="Link" DataTextField="Link" HeaderText="Link" SortExpression="Link" UniqueName="Link" FilterControlAltText="Filter Link column"></telerik:GridHyperLinkColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
C#:
protected void RadGrid3_NeedDataSource(object sender,
GridNeedDataSourceEventArgs e)
{
//Populate parent table with temp data
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name");
for (int i = 1; i <= 20; i++) {
table.Rows.Add(i, "Name" + i.ToString());
}
RadGrid3.DataSource = table;
}
protected void RadGrid3_ItemDataBound(object sender, GridItemEventArgs e)
{
//If its a row item
if (e.Item.ItemType == GridItemType.Item | e.Item.ItemType == GridItemType.AlternatingItem) {
dynamic item = (GridDataItem)e.Item;
//Find the nested Radgrid in the row
RadGrid subGrid = (RadGrid)item("Links").FindControl("RadGrid4");
//Get the current row's datakey value
int currentRowDataKeyValue = item.GetDataKeyValue("ID");
//Create temp data for nested radgrid
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name");
table.Columns.Add("Link");
for (int i = 1; i <= 5; i++) {
table.Rows.Add(i, "Row " + currentRowDataKeyValue.ToString + ": Link " + i.ToString, "https://www.google.com");
}
//Set datasource for nested radgrid. This is where you would databind the list of strings from your domain. You will probably need to manipulate the data returned to match the nested grid structure if you want additional columns
subGrid.DataSource = table;
subGrid.DataBind();
}
Alternatively, you can add the links to the DetailTemplateColumn. This is pretty much the same solution, but it displays the nested RadGrid underneath the row instead of in a template column.
ASPX:
<telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource" AutoGenerateColumns="false" OnItemDataBound="RadGrid1_ItemDataBound1">
<MasterTableView DataKeyNames="ID">
<Columns>
<telerik:GridBoundColumn UniqueName="Id" DataField="ID" HeaderText="ID"></telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Name" DataField="Name" HeaderText="Name"></telerik:GridBoundColumn>
</Columns>
<DetailItemTemplate>
<telerik:RadGrid ID="RadGrid2" runat="server" Skin="Windows7" RenderMode="Lightweight">
<MasterTableView DataKeyNames="Id" AutoGenerateColumns="False" ShowHeader="false">
<Columns>
<telerik:GridBoundColumn DataField="ID" ReadOnly="True" HeaderText="Id" SortExpression="Id" UniqueName="Id" DataType="System.Int32" FilterControlAltText="Filter Id column"></telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Name" ReadOnly="True" HeaderText="Name" SortExpression="Name" UniqueName="Name" DataType="System.Int32" FilterControlAltText="Filter Name column"></telerik:GridBoundColumn>
<telerik:GridHyperLinkColumn DataNavigateUrlFields="Link" DataTextField="Link" HeaderText="Link" SortExpression="Link" UniqueName="Link" FilterControlAltText="Filter Link column"></telerik:GridHyperLinkColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</DetailItemTemplate>
</MasterTableView>
</telerik:RadGrid>
C#
protected void RadGrid1_NeedDataSource(object sender,
GridNeedDataSourceEventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name");
for (int i = 1; i <= 20; i++) {
table.Rows.Add(i, "Name" + i.ToString());
}
RadGrid1.DataSource = table;
}
protected void RadGrid1_ItemDataBound1(object sender, GridItemEventArgs e)
{
if (e.Item.ItemType == GridItemType.Item | e.Item.ItemType == GridItemType.AlternatingItem) {
dynamic item = (GridDataItem)e.Item;
//Find the grid in the DetailTemplate Cell
RadGrid subGrid = (RadGrid)item.DetailTemplateItemDataCell.FindControl("RadGrid2");
// Get the current row datakey value
int currentRowDataKeyValue = Convert.ToInt32(item.GetDataKeyValue("ID"));
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name");
table.Columns.Add("Link");
for (int i = 1; i <= 5; i++) {
table.Rows.Add(i, "Row " + currentRowDataKeyValue.ToString + ": Link " + i.ToString, "https://www.google.com");
}
subGrid.DataSource = table;
subGrid.DataBind();
}
}

asp.net gridview pagination not displayed until refreshing

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

Gridview datasource is null after postback

I have a page with a gridview that show article groups,and textbox and search button for search groups.
in this page if user not search anything ,grid view only show main groups(with parentId 0)
and else show every group that group name's contain textbox value.
My problem is when I search ,and then I want to update some row,GridView1_RowUpdating not fired...
I found that the problem is that gridview datasource not bound successfully.
how I fix this problem?
below is my source:
<asp:Label ID="Label1" runat="server" CssClass="txt" Text="searchgroups " ForeColor="#68a2d7"></asp:Label>
<asp:Label ID="Label2" runat="server" CssClass="txt" Text="group name" ForeColor="#68a2d7"></asp:Label>
<asp:TextBox ID="txtname" runat="server" CssClass="txt" Width="300px"></asp:TextBox>
<br/>
<asp:ImageButton ID="Ibtnsearch" runat="server" ImageAlign="Left" ImageUrl="../Icon/resize/search.gif"
OnClick="Ibtnsearch_Click" />
<br/>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" Width="100%" CssClass="txt" AllowPaging="True"
OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" OnPageIndexChanging="GridView1_PageIndexChanging"
OnRowCommand="GridView1_RowCommand1" PageSize="15" AllowSorting="True" OnSorting="GridView1_Sorting">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="chid" SortExpression="chid" HeaderText="ID" />
<asp:BoundField DataField="chname" SortExpression="chname" HeaderText="Name" />
<asp:HyperLinkField DataNavigateUrlFields="chid,cLanguage" DataNavigateUrlFormatString="../default.aspx?pnl=lstcatChat&nParentid_fk={0}&lang={1}"
Text="Sub Groups" HeaderText="Show Sub Grups">
<ControlStyle CssClass="link" />
</asp:HyperLinkField>
<asp:CommandField CausesValidation="false" ButtonType="Image" EditImageUrl="~/Icon/silk/application_edit.gif"
ShowEditButton="True" CancelImageUrl="~/Icon/silk/arrow_undo.gif" UpdateImageUrl="~/Icon/silk/accept.gif"
EditText="Edit" HeaderText="Edit" />
</Columns>
<RowStyle BackColor="#e8edf2" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<PagerStyle BackColor="White" ForeColor="#333333" HorizontalAlign="Center" BorderColor="White"
Font-Bold="True" Font-Names="Tahoma" Font-Overline="False" Font-Size="X-Small"
Font-Underline="False" />
<HeaderStyle BackColor="#68a2d7" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="White" />
<PagerSettings Mode="NumericFirstLast" />
</asp:GridView>
and in my code page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = Search_groups();
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.DataSource = Search_groups();
if (GridViewSortExpresion != null && GridViewSortExpresion != "")
SortGridView(GridViewSortExpresion, GridViewSortDirection);
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.DataSource = Search_groups();
if (GridViewSortExpresion != null && GridViewSortExpresion != "")
SortGridView(GridViewSortExpresion, GridViewSortDirection);
GridView1.EditIndex = -1;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow gvr = GridView1.Rows[e.RowIndex];
using (_Category nc = new _Category())
{
if (Request["lang"] == "" || Request["lang"] == null)
nc.Language = "fa";
else
nc.Language = Request["lang"];
DataTable dt2 = new DataTable();
dt2 = Search_groups();
int ncid = (int)dt2.Rows[e.RowIndex]["chid"];
ncid = Convert.ToInt32(((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text);
nc.ID = ncid;
nc.Name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
nc.Updatefast();
GridView1.DataSource = Search_groups();
if (GridViewSortExpresion != null && GridViewSortExpresion != "")
SortGridView(GridViewSortExpresion, GridViewSortDirection);
GridView1.EditIndex = -1;
GridView1.DataBind();
dt2.Dispose();
gvr.Dispose();
}
}
protected void Ibtnsearch_Click(object sender, ImageClickEventArgs e)
{
GridView1.DataSource = Search_groups();
if (GridViewSortExpresion != null && GridViewSortExpresion != "")
SortGridView(GridViewSortExpresion, GridViewSortDirection);
GridView1.DataBind();
}
private DataTable Search_groups()
{
if (Request["nParentid_fk"] != null)
parent_fk = Convert.ToInt32(Request["nParentid_fk"]);
else
parent_fk = 0;
using (_Category nc = new _Category())
{
if (Request["lang"] == "" || Request["lang"] == null)
nc.Language = "fa";
else
nc.Language = Request["lang"];
if (txtname.Text != "")
return nc.search_allcategories(txtname.Text);
else
return nc.Select_parentid_fk(parent_fk);
}
}
public string GridViewSortDirection
{
get
{
//if (ViewState["sortDirection"] == null)
// ViewState["sortDirection"] = SortDirection.Ascending;
//return (SortDirection)ViewState["sortDirection"];
if (SortDirection.Value == null)
SortDirection.Value = "asc";
return SortDirection.Value;
}
set { SortDirection.Value = value; }
}
public string GridViewSortExpresion
{
get
{
//if (ViewState["SortExpresion"] == null)
// ViewState["SortExpresion"] = "";
//if (ViewState["SortExpresion"] != null)
// return ViewState["SortExpresion"].ToString();
//else
// return null;
if (SortExpresion.Value != null)
return SortExpresion.Value.ToString();
else
return null;
}
set { SortExpresion.Value = value; }
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//DataTable dataTable = GridView1.DataSource as DataTable;
GridViewSortExpresion = e.SortExpression;
if (GridViewSortDirection == "asc")
{
GridViewSortDirection = "desc";
SortGridView(GridViewSortExpresion, GridViewSortDirection);
}
else
{
GridViewSortDirection = "asc";
SortGridView(GridViewSortExpresion, GridViewSortDirection);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
//DataTable dt = GridView1.DataSource as DataTable;
DataTable dt = Search_groups();
DataView dv = new DataView(dt);
dv.Sort = sortExpression + " " + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
when I try to update ,I get this error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Edit 2
Now I found that my problem is that gridview loses datasource on post back ,
I search but I not found solution.I don't want to use session or viewstate,because I have a lot of tables like above ,What is the solution?
set following property:
set AutoGenerateEditButton="False"
Try putting:
<asp:TemplateField>
<ItemTemplate>
<asp:Button id="btnEdit" runat="server" commandname="Edit" text="Edit" />
<asp:Button id="btnDelete" runat="server" commandname="Delete" text="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button id="btnUpdate" runat="server" commandname="Update" text="Update" />
<asp:Button id="btnCancel" runat="server" commandname="Cancel" text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
In place of :
<asp:CommandField CausesValidation="false" ButtonType="Image" EditImageUrl="~/Icon/silk/application_edit.gif"
ShowEditButton="True" CancelImageUrl="~/Icon/silk/arrow_undo.gif" UpdateImageUrl="~/Icon/silk/accept.gif"
EditText="Edit" HeaderText="Edit" />

GridView not getting refreshed on Listbox selection

I have a GridView,
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="ProgramName" HeaderText="ProgramName"
SortExpression="ProgramName" />
</Columns>
</asp:GridView>
This is the ListBox method which I am using to refresh the GridView,
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedValue == "Computer Programmer")
{
DataSet test = GetStudentByProgramID(1);
if (test.Tables.Count > 0)
{
GridView1.Columns.Clear();
GridView1.DataSource = test;
GridView1.Attributes.Add("style", "table-layout:fixed");
//ISBNColumn
BoundField LastName = new BoundField();
//LastName.DataField = test.Tables.r.ColumnName;
LastName.HeaderText = "ISBN";
LastName.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
GridView1.Columns.Add(LastName);
//CopyNumberColumn
BoundField FirstName = new BoundField();
//FirstName.DataField = myitems.Items.CopyNumberColumn.ColumnName;
FirstName.HeaderText = "Copy Number";
FirstName.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
GridView1.Columns.Add(FirstName);
GridView1.DataBind();
}
}
}
But GridView does not get refreshed when I select the value from ListBox. Any mistake I am making here?
Also my listbox is getting filled like this,
DataSet ab = GetProgramList();
ListBox1.Items.Clear();
if (ab.Tables[0].Rows.Count > 0)
{
ListBox1.DataSource = ab;
ListBox1.DataTextField ="ProgramName";
ListBox1.DataValueField ="ProgramName";
ListBox1.DataBind();
}
make sure your listbox has
AutoPostBack="True"
<asp:ListBox id="ListBox1"
Rows="4"
AutoPostBack="True"
SelectionMode="Single"
runat="server">
if(!IsPostBack)
{
DataSet ab = GetProgramList();
ListBox1.Items.Clear();
if (ab.Tables[0].Rows.Count > 0)
{
ListBox1.DataSource = ab;
ListBox1.DataTextField ="ProgramName";
ListBox1.DataValueField ="ProgramName";
ListBox1.DataBind();
}
}

edit row in gridview

I would like to help me with my code. I have 2 gridviews. In the first gridview the user can choose with a checkbox every row he wants. These rows are transfered in the second gridview. All these my code does them well.Now, I want to edit the quantity column in second gridview to change the value but i don't know what i must write in edit box.
Here is my code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
public partial class ShowLand : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPrimaryGrid();
BindSecondaryGrid();
}
}
private void BindPrimaryGrid()
{
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string query = "select * from Land";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
sda.Fill(dt);
gridview2.DataSource = dt;
gridview2.DataBind();
}
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords1"] != null)
dt = (DataTable)ViewState["SelectedRecords1"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gridview2.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < gridview2.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gridview2.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gridview2.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gridview2.Rows[i], dt);
}
else
{
dt = RemoveRow(gridview2.Rows[i], dt);
}
}
}
ViewState["SelectedRecords1"] = dt;
}
private void SetData()
{
CheckBox chkAll = (CheckBox)gridview2.HeaderRow.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
if (ViewState["SelectedRecords1"] != null)
{
DataTable dt = (DataTable)ViewState["SelectedRecords1"];
for (int i = 0; i < gridview2.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gridview2.Rows[i].Cells[0].FindControl("chk");
if (chk != null)
{
DataRow[] dr = dt.Select("id = '" + gridview2.Rows[i].Cells[1].Text + "'");
chk.Checked = dr.Length > 0;
if (!chk.Checked)
{
chkAll.Checked = false;
}
}
}
}
}
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("price");
dt.Columns.Add("quantity");
dt.Columns.Add("total");
dt.AcceptChanges();
return dt;
}
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["id"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["name"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["price"] = gvRow.Cells[3].Text;
dt.Rows[dt.Rows.Count - 1]["quantity"] = gvRow.Cells[4].Text;
dt.Rows[dt.Rows.Count - 1]["total"] = gvRow.Cells[5].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords1"];
gridview3.DataSource = dt;
gridview3.DataBind();
}
}
and the source code is
<asp:GridView ID="gridview2" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource5">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False"
ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="name"
SortExpression="name" />
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="quantity" HeaderText="quantity"
SortExpression="quantity" />
<asp:BoundField DataField="total" HeaderText="total" SortExpression="total" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Land]"></asp:SqlDataSource>
<br />
</div>
<div>
<asp:GridView ID="gridview3" runat="server"
AutoGenerateColumns = "False" DataKeyNames="id"
EmptyDataText = "No Records Selected" >
<Columns>
<asp:BoundField DataField = "id" HeaderText = "id" />
<asp:BoundField DataField = "name" HeaderText = "name" ReadOnly="True" />
<asp:BoundField DataField = "price" HeaderText = "price"
DataFormatString="{0:c}" ReadOnly="True" />
<asp:TemplateField HeaderText="quantity">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("quantity")%>'</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "total" HeaderText = "total"
DataFormatString="{0:c}" ReadOnly="True" />
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:Label ID="totalLabel" runat="server"></asp:Label>
<br />
</div>
</form>
</body>
</html>
This is not particular asp.net solution but that's how I do something like this in my Windows app.
First of all you shoul make shure that there's a selected row in your GridView (gridView.SelectedRow != null). DataTable object allows you to get access to desired row by accessing it not by numeric index but by DataRow-type object index. After getting a reference to the row which fields' value you want to modify just go ahead with changes.
Here's the example:
if (gridView.SelectedRow != null)
{
dataTable.Rows[gridView.SelectedRow].BeginEdit();
dataTable.Rows[gridView.SelectedRow]["yourFieldName"] = newValue;
dataTable.Rows[gridView.SelectedRow].EndEdit();
gridView.DataSource = dataTable;
}
Hope my answer is of any help because I've never dealt with asp.net before.

Categories