gridview cannot add an 'approve' button in gridview,can someone can help me thanks
http://i260.photobucket.com/albums/ii8/elvenchan2/rowAdd.png
behind code
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow dr in GridView2.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn.Text = "Approve";
btn.ID = "Approve";
btn.Click += new EventHandler(Approve_Click);
if (dr.Cells[1].Text == "1")
{
dr.Cells[10].Controls.Add((Control)btn);
}
}
}
}
u must add a 10th cell at first
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow dr in GridView2.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn.Text = "Approve";
btn.ID = "Approve";
btn.Click += new EventHandler(Approve_Click);
if (dr.Cells[1].Text == "1")
{
//Declare the bound field and allocate memory for the bound field.
ButtonField btnRent = new ButtonField();
//Initalize the DataField value.
btn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
btn.CommandName = "Button";
btn.ButtonType = ButtonType.Button;
btn.Text = "Rent";
btn.Visible = true;
//Add the newly created bound field to the GridView.
GridView2.Columns.Add(btn);
}
}
}
}
Since there is no criteria for creating the button, why not just make a TemplateField in your GridView markup and wire up a click handler or CommandName for the button, like this:
<asp:GridView id="GridView1" runat="server"
OnRowCommand="GridView1_RowCommand">
<Columns>
...
<asp:TemplateField>
<ItemTemplate>
<asp:Button id="ButtonApprove" runat="server"
CommandName="approve" Text="Approve" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now in your code-behind, you can handle each individual approve button click, like this:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "approve")
{
// Do approval logic here
}
}
You can try it:
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState != DataControlRowState.Edit)
{
PlaceHolder ph = (PlaceHolder)e.Row.FindControl("PlaceHolder1");
Button b1 = new Button();
b1.ID = "Approve";
b1.Text = "Approve"
ph.Controls.Add(b1);
}
}
Of course, you should add a placeholder in the html template. like
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
Button add here..
</asp:PlaceHolder>
</ItemTemplate>
Design
<asp:GridView ID="viewThemeTypeAssociationsGridView" runat="server" AutoGenerateColumns="False"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2"
OnRowDataBound="viewThemeTypeAssociationsGridView_RowDataBound"
DataSourceID="Sql_New" >
<Columns>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id"
InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:TemplateField HeaderText ="New Column" >
<ItemTemplate >
<asp:Button ID="btnnew" runat ="server" Visible ="false" ></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:SqlDataSource ID="Sql_New" runat="server"
ConnectionString="<%$ ConnectionStrings:EmployeeConnectionString %>"
SelectCommand="SELECT * FROM [tblnew]"></asp:SqlDataSource>
Code
protected void viewThemeTypeAssociationsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[2].Text == " ")
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnnew = (Button)e.Row.FindControl("btnnew");
btnnew.Visible = true;
}
}
}
Related
I have 2 buttons, one is called "Accept", which is used for updating of database while another is called "View", which is used for Redirecting. However, in GridView's SelectedIndexChanged, i wasnt able to Validate which buttons were click
so I have tried Using RowCommand for the "View" button and SelectedIndexChanged for "Accept" button. But RowCommand is triggering the "Accept" button in the SelectedIndexChanged event handler.
<asp:GridView ID="QgridView" AutoGenerateColumns="False"
CssClass="table table-bordered" AllowPaging="True" PageSize="6"
BackColor="White" BorderColor="Black" BorderStyle="Solid"
ForeColor="Black" GridLines="None" runat="server"
OnRowCommand="QgridView_RowCommand"
OnSelectedIndexChanged="QgridView_SelectedIndexChanged" >
<Columns>
<asp:TemplateField HeaderText="No">
<ItemTemplate>
<span>
<%#Container.DataItemIndex + 1%>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText="Image" DataImageUrlField="coverimg" >
<ControlStyle CssClass="coverimage"/>
<ItemStyle HorizontalAlign="Center" />
</asp:ImageField>
<asp:BoundField HeaderText="Buyer" DataField="buyer" />
<asp:BoundField HeaderText="Item" DataField="item" />
<asp:BoundField HeaderText="Price offered" DataField="price" />
<asp:buttonfield buttontype="Button"
commandname="Accept"
text="Accept"/>
<asp:BoundField DataField="quoteid" HeaderText="quoteid" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="id" HeaderText="id" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="rtype" HeaderText="rtype" ItemStyle-
CssClass="hiddencol" HeaderStyle- CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="seller" HeaderText="seller" ItemStyle-
CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:buttonfield buttontype="Button"
commandname="View"
text="View"/>
</Columns>
</asp:GridView>
// Behind COde page
protected void QgridView_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = QgridView.SelectedRow;
string seller = row.Cells[10].Text;
string item = row.Cells[4].Text;
string type = row.Cells[9].Text;
int id = Convert.ToInt32(row.Cells[8].Text);
int quoteid = Convert.ToInt32(row.Cells[7].Text);
productDAO productdao = new productDAO();
productdao.GridPush(quoteid, id)
}
protected void QgridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
Response.Redirect("ListingItems.aspx");
}
}
I want the "Accept" BUtton to perform the updating of database while the "View button to perform Response.Redirect. However, RowCommand does not fire and instead, it triggers the "Accept" button in SelectedIndexChanged. May i know how can perform the different task for each button?
[Gettting row data from GridView]
protected void QgridView_RowCommand(object sender,
GridViewCommandEventArgs e)
{
System.Diagnostics.Debug.WriteLine("onrowcommand");
if (e.CommandName == "View")
{
System.Diagnostics.Debug.WriteLine("ButtonView is clicked");
Response.Redirect("ListingItems.aspx");
}
else if (e.CommandName == "Accept")
{
System.Diagnostics.Debug.WriteLine("buttonAccept is clicked");
productDAO productdao = new productDAO();
//GridViewRow row = QgridView.SelectedRow;
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = QgridView.Rows[index];
string id = row.Cells[8].Text; //Returns me nothing
}
else
{
System.Diagnostics.Debug.WriteLine("no command name");
}
}
I think you are no need to check the rowcommand or onselected Index change event you can directly set button on click event. if you are using the inside your Gridview, then you should be able to register an event in your button code as:
<asp:Button runat="server" OnClick="YourclickEvent" />
For more details on event you should read this: https://www.codeproject.com/Articles/50540/GridView-Event-Handling
One Addition: if using row command then identify each button with command name and you can perform your task easily.
According to your code SelectedIndexChanged should be never fired (no select command).
RowCommand handler always fire first (before more specific handlers).
Look at sample working code.
.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="CategoryID"
DataSourceID="sqlCategory"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" AllowPaging="True">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" SortExpression="CategoryName" />
<asp:ButtonField ButtonType="Button" CommandName="Accept" HeaderText="Accept" ShowHeader="True" Text="Accept" />
<asp:ButtonField ButtonType="Button" CommandName="View" HeaderText="View" ShowHeader="True" Text="View" />
<%-- Use HyperLinkField instead of ButtonField --%>
<asp:HyperLinkField DataNavigateUrlFields="CategoryID" DataNavigateUrlFormatString="category.aspx?categoryid={0}" DataTextField="CategoryName" DataTextFormatString="View {0}" HeaderText="Direct View" />
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
</asp:GridView>
<%-- Data from NorthWind learning DB --%>
<asp:SqlDataSource ID="sqlCategory" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnection %>"
SelectCommand="SELECT CategoryID, CategoryName FROM Categories"
UpdateCommand="update categories set categoryName=#CategoryName where CategoryID=#CategoryID">
<UpdateParameters>
<asp:Parameter Name="CategoryID" Type="Int32" />
<asp:Parameter Name="CategoryName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
.aspx.cs
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Trace.Write("GridView1_SelectedIndexChanged");// fired by "select" command after RowCommand finished
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Trace.Write("GridView1_RowCommand");
//
if (e.CommandName == "Accept")
{
var categoryId = (int)GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;//e.CommandArgument is display index
Trace.Write(e.CommandName + ": " + e.CommandArgument + " : " + categoryId.ToString());
}
else if (e.CommandName == "View")
{
Trace.Write("View " + e.CommandArgument);
}
}
I have GridView with 5 items like this.
I want to make this GridView as below big red square. How can I make 2rows in one GridView?
ASP Code :
<asp:GridView ID="GridView" runat="server" DataSourceID="GridView1"
OnRowCreated="GridView1_RowCreated" AutoGenerateColumns="false" EmptyDataText="표시할 내용없음">
<Columns>
<asp:BoundField DataField="Seq"/>
<asp:BoundField DataField="Title" />
<asp:BoundField DataField="UUSER" />
<asp:BoundField DataField="NoticeDate" />
<asp:BoundField DataField="SCnt" />
</Columns>
</asp:GridView>
C#
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Visible = false;
e.Row.Cells[1].Visible = false;
e.Row.Cells[2].Visible = false;
e.Row.Cells[3].Visible = false;
e.Row.Cells[4].Visible = false;
//e.Row.Cells[1].Attributes.Add("colspan", "2");
}
I have a gridview with ckeck column,my user can select the item via checked box so i add a checkbox column to my gridview:
<asp:GridView ID="taminkonandeh" runat="server" CssClass="gv-list-company-col-edit" ShowHeaderWhenEmpty="True" AutoGenerateColumns="False" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChTaminKonande" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="شماره " DataField="companyid" >
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
<asp:BoundField HeaderText="نام شرکت " DataField="companyname">
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
<asp:BoundField HeaderText="شماره ثبت " DataField="registrationNumber" >
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
<asp:BoundField HeaderText="شماره اقتصادی" DataField="noEconomic" >
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
</Columns>
<HeaderStyle CssClass="gv-list-company-header" />
<RowStyle CssClass="gv-list-company-row"/>
</asp:GridView>
and my code behind is :
for (int i = 0; i < taminkonandeh.Rows.Count; i++)
{
CheckBox chinvi = (CheckBox)taminkonandeh.Rows[i].FindControl("ChTaminKonande");
if (chinvi != null)
{
if (chinvi.Checked)
{
Count++;
comid = taminkonandeh.Rows[i].Cells[1].Text;
tblAnnouncePriceByCompany objanno = new tblAnnouncePriceByCompany();
objanno.letterId = objletter.letterId.ToString();
objanno.companyId = comid;
objanno.tenderId = Session["letterTenderId"].ToString();
db1.tblAnnouncePriceByCompanies.InsertOnSubmit(objanno);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "myalert",
"alert('تامین کننده ای انتخاب نشده است ')", true);
return;
}
}
but "chinvi.Checked" condition is always false and i can't detect which checkboxs are selected.
This situation happens when you bind the gridview in pageload, and each postback rebinds it, removes posted value like this:
protected void Page_Load(object sender, EventArgs e)
{
//Code to get datasource
taminkonandeh.DataSource = myDataSource;
taminkonandeh.DataBind();
}
You need to change it to :
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Code to get datasource
taminkonandeh.DataSource = myDataSource;
taminkonandeh.DataBind();
}
}
I just read some articles about paging gridview but I couldn't make it...
There is my full gridview's code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" style="font-family: Verdana, Arial, Sans-Serif;"
CssClass="gridview" OnSorting="GridView_Sorting"
DataKeyNames="id"
AllowSorting ="True" BackColor="#CCCCCC"
BorderStyle="Inset" BorderWidth="2px" BorderColor="GrayText"
CellPadding="1"
CellSpacing="5"
HeaderStyle-HorizontalAlign="Center"
OnRowDataBound="GridView1_RowDataBound"
ForeColor = "Black" RowStyle-CssClass="gridview"
OnRowCommand="GridView1_RowCommand" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5">
<AlternatingRowStyle BackColor="#CCCCCC" />
<columns>
<asp:BoundField HeaderText="ID" DataField="id" />
<asp:BoundField HeaderText="PRIORIDADE" DataField="prioridade"
ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="SITUAÇÃO" DataField="situacao" ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="RESPONSAVEL" DataField="responsavel" HeaderStyle-Width="65px" ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="65px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="DATA DE CADASTRO" DataField="dt_cadastro" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px" SortExpression="dt_cadastro"
ItemStyle-HorizontalAlign="Center" >
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PREVISÃO DE TÉRMINO" DataField="previsao_termino" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"
ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PROJETO" DataField="projeto" ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="FUNCIONALIDADE" DataField="funcionalidade"
ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="CLUBE" DataField="clube"
ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderStyle-Width="70px" HeaderText="VISUALIZAR" >
<ItemTemplate>
<asp:Button ID="Btn_Visualizar" runat="server" Text="VISUALIZAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial" OnClick="Btn_Visualizar_Click"
CommandName="visualizar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
<HeaderStyle Width="70px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="ALTERAR">
<ItemTemplate>
<asp:Button ID="Btn_Alterar" runat="server" Text="ALTERAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial"
CommandName="editar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
<HeaderStyle Width="66px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="FEEDBACK">
<ItemTemplate>
<asp:Button ID="Btn_Feedback" runat="server" Text="ADICIONAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana,Arial"
CommandName="feedback" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
<HeaderStyle Width="66px" />
</asp:TemplateField>
</columns>
<EditRowStyle ForeColor="Black" CssClass="GridViewEditRow" />
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" BorderColor="White" BorderStyle="Solid" BorderWidth="1px" />
<PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="5" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
</asp:GridView>
CodeBehind:
public partial class TodosChamados : System.Web.UI.Page
{
BDUsuarios usr = new BDUsuarios();
BDFuncionalidades func = new BDFuncionalidades();
BDChamados ch = new BDChamados();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = ch.BuscaTodosChamados();
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[1].Text == "ALTA")
{
e.Row.Cells[1].BackColor = System.Drawing.Color.Red;
e.Row.ControlStyle.Font.Bold = true;
}
}
if (e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager)
{
e.Row.Cells[0].Visible = false;
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName != "Sort")
{
if (e.CommandName == "visualizar")
{
Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text;
Session["editar"] = null;
}
else if (e.CommandName == "editar")
{
Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text; //Grava o ID do chamado da linha correspondente.
Session["editar"] = 1; // 1 - Editar 2 - Não Editar .
}
else if (e.CommandName == "feedback")
{
Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text; //Grava o ID do chamado da linha correspondente.
Response.Redirect("~/Adm/Feedback.aspx");
}
Response.Redirect("~/Adm/DetalhesChamado.aspx");
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = ch.BuscaTodosChamados();
GridView1.DataBind();
}
Update 2
Now i hopefully have found the reason for your pager not being shown. You are making the first colum invisible, even for the pager-row in RowDataBound, but the pager is sitting in the first cell by default:
e.Row.Cells[0].Visible = false;
You have to check the correct RowType:
e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager;
or even better on the aspx markup:
<asp:BoundField HeaderText="ID" DataField="id" Visible="False" />
A silly question, have you set AllowPaging to true?
<asp:GridView Id="GridView1" runat="server" AllowPaging="True" >
<PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="5" />
</asp:gridview>
GridView.AllowPaging Property
true if the paging feature is enabled; otherwise, false. The default is false.
You should also databind the GridView only if(!IsPostBack) when viwstate is enabled(default).
So wrap your databind code from Page_Load(i guess) into this check:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
GridView1.DataSource = ch.BuscaTodosChamados();
GridView1.DataBind();
}
}
Otherwise events won't be triggered and changes will be overwritten when you reload data on postback.
Update According to your last edit:
I assume that your RowCommand is the reason for this issue. It is called before the PageIndexChanging event and it is triggered also when the page changes(if i remember correctly). So have a look at your Response.Redirect which happens when no if/else-if will catch it which seems to be the case.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName != "Sort")
{
if (e.CommandName == "visualizar")
{
// ..
}
else if (e.CommandName == "editar")
{
//..
}
else if (e.CommandName == "feedback")
{
//..
}
Response.Redirect("~/Adm/DetalhesChamado.aspx");
}
}
You must specify the event for OnPageIndexChanging in your .aspx. It should be:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
OnPageIndexChanging = "GridView1_PageIndexChanging"
AutoGenerateColumns="False" DataKeyNames="LastName,FirstName"
EnablePersistedSelection="True" SelectedRowStyle-BackColor="Yellow"
DataSourceID="SqlDataSource1" AllowSorting="True">
You might be having the same problem here
UPDATE
Make sure that the data that's being bound to the GridView is more that 5 since PageSize="5". If the number of rows is less than 5, then the pager will not be shown.
I add below line to each row and when i click on row in GridView i can select it(means event GridView_SelectedIndexChanged hire) how can i change it that when i click on row specific method call
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
in view:
<script type="text/javascript" language="javascript">
function show(id) {
alert(id);
// Do something as your need
}
</script>
<asp:GridView runat="server" ID="GridView1" DataKeyNames="DepartmentID" AutoGenerateColumns="False"
Font-Names="Tahoma" Font-Size="Small"
OnRowDataBound="GridView1_RowDataBound" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="DepartmentID" HeaderText="DepartmentID"
InsertVisible="False" ReadOnly="True" SortExpression="DepartmentID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Budget" HeaderText="Budget"
SortExpression="Budget" />
<asp:BoundField DataField="StartDate" HeaderText="StartDate"
SortExpression="StartDate" />
<asp:BoundField DataField="Administrator" HeaderText="Administrator"
SortExpression="Administrator" />
</Columns>
</asp:GridView>
inCodeBehind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'");
e.Row.Attributes["onclick"] = "show(" + e.Row.RowIndex.ToString() + ");";
}
}
Use GridView.RowCommand Event: The RowCommand event is raised when a button is clicked in the GridView control. This enables you to provide an event-handling method that performs a custom routine whenever this event occurs.
void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="YourCommandName")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = GridView1.Rows[index];
//Your Code
}
}
<asp:GridView runat="server" ID="GridView1" DataKeyNames="ID" AutoGenerateColumns="False"
Font-Names="Tahoma" Font-Size="Small" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Row">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:CommandField ShowSelectButton="true" ButtonType="Link" Visible="false" SelectText="Enroll" />
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//add css to GridViewrow based on rowState
e.Row.CssClass = e.Row.RowState.ToString();
//Add onclick attribute to select row.
e.Row.Attributes.Add("onclick", String.Format("javascript:__doPostBack('GridView1','Select${0}')", e.Row.RowIndex));
}
}