I am have put buttonfield in gridview. It hit the rowcommand event and goes to the end of block but doesn't do what it is supposed to do. It is supposed to assign text to the text box and shows message via response.write but doesn't. In debugger it perfectly assign text to the textbox and goes to the message but nothing on interface side. Why ?
<asp:GridView runat="server" ID="grdviewContractorTypes" OnRowCommand="grdviewContractorTypes_RowCommand" DataKeyNames="pk_ContractorTypes_ContractorTypeID" AutoGenerateColumns="false" CssClass="table table-condensed table-bordered table-striped table-responsive">
<Columns>
<asp:BoundField DataField="pk_ContractorTypes_ContractorTypeID" HeaderText="ID" />
<asp:BoundField DataField="ContractorTypeName" HeaderText="Contractor Type" />
<asp:ButtonField CommandName="edit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="25px" />
</Columns>
</asp:GridView>
event:
protected void grdviewContractorTypes_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "edit")
{
byte ContractorTypeID = Convert.ToByte(grdviewContractorTypes.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
//HFActID.Value = ID.ToString();
btnAddContractorType.Visible = false;
btnUpdate.Visible = true;
DataTable dt = MngContractorTypes.SelectContractorTypesByContractorTypeID(ContractorTypeID);
DataRow r = dt.Rows[0];
txtBoxContractorTypeName.Text = r["ContractorTypeName"].ToString();
Response.Write("DONE");
}
}
catch (Exception)
{
}
}
It doesn't do anything, apparently but shows and assigns in debugger. Why ?
Try adding OnRowEditing to your grid.
<asp:GridView runat="server" ID="grdviewContractorTypes" OnRowEditing="grdviewContractorTypes_RowEditing" OnRowCommand="grdviewContractorTypes_RowCommand" DataKeyNames="pk_ContractorTypes_ContractorTypeID" AutoGenerateColumns="false" CssClass="table table-condensed table-bordered table-striped table-responsive">
<Columns>
<asp:BoundField DataField="pk_ContractorTypes_ContractorTypeID" HeaderText="ID" />
<asp:BoundField DataField="ContractorTypeName" HeaderText="Contractor Type" />
<asp:ButtonField CommandName="edit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="25px" />
</Columns>
</asp:GridView>
Code Behind:
protected void grdviewContractorTypes_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "edit")
{
byte ContractorTypeID = Convert.ToByte(grdviewContractorTypes.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
//HFActID.Value = ID.ToString();
//btnAddContractorType.Visible = false;
//btnUpdate.Visible = true;
//DataTable dt = MngContractorTypes.SelectContractorTypesByContractorTypeID(ContractorTypeID);
//DataRow r = dt.Rows[0];
//txtBoxContractorTypeName.Text = r["ContractorTypeName"].ToString();
Response.Write("DONE");
}
}
catch (Exception)
{
}
}
protected void grdviewContractorTypes_RowEditing(object sender, GridViewEditEventArgs e)
{
// code to edit
}
Related
I have a GridView called gridview1
What I want is that if the user select or click on specific row some action will happen.
For example I want to get the value from that row and store it in a new variable.
How can I do it? I'm confused about what I should do to get the value?
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string stuId = ?
}
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<u>Selected Row Values: </u>
<br />
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
you simply copy and paste your issue is resolve.
you could use like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "StudID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}
I dont know why paging is not working when i use master page. If I put the same code in another file which in not linked with master page it works like a charm. But when I link it to master page it doesn't work.
here is my mark up
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div id="menu_content">
<div class="tabs">
My Addresses</div>
<div class="midContent">
<asp:GridView ID="addressGrd" OnPageIndexChanging="addressGrd_PageIndexChanging"
Width="816px" ForeColor="#ffffff" AllowSorting="true" HeaderStyle-BackColor="#222222"
HeaderStyle-Height="60px" runat="server" AutoGenerateColumns="False" GridLines="None"
AllowPaging="True" PagerSettings-FirstPageText="First" PagerSettings-LastPageText="Last"
PagerSettings-Mode="NextPreviousFirstLast" PageSize="5" PagerSettings-PageButtonCount="4">
<Columns>
<asp:BoundField DataField="customerName" HeaderText="Name" ReadOnly="True" />
<asp:BoundField DataField="customerCompany" HeaderText="Company" ReadOnly="True" />
<asp:BoundField DataField="customerPhone" HeaderText="Phone" ReadOnly="True" />
<asp:BoundField DataField="addressLine1" HeaderText="Address 1" ReadOnly="True" />
<asp:BoundField DataField="addressLine2" HeaderText="Address 2" ReadOnly="True" />
<asp:BoundField DataField="city" HeaderText="City" ReadOnly="True" />
<asp:BoundField DataField="state" HeaderText="State" ReadOnly="True" />
<asp:BoundField DataField="zipCode" HeaderText="Zip Code" ReadOnly="True" />
<asp:TemplateField>
<HeaderTemplate>
Main Address
</HeaderTemplate>
<ItemTemplate>
<asp:ImageButton runat="server" OnClick="changeStatus" ID="imgStatus" CommandArgument='<%#Eval("mainAddress")+","+ Eval("addressID")%>'
ImageUrl='<%# Bind_Image(Eval("mainAddress").ToString()) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Action
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="editItem" Text=" " OnClick="Edit" CommandArgument='<%# Eval("addressID")%>'
CssClass="editButton" runat="server">
</asp:LinkButton>
<asp:LinkButton Text=" " ID="deleteItem" CssClass="deleteButton"
runat="server" CommandArgument='<%# Eval("addressID")%>' OnClientClick="return confirm('Do You Want To Delete ?')"
OnClick="Delete">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode="NumericFirstLast" PageButtonCount="4" FirstPageText="First"
LastPageText="Last" />
<PagerStyle BackColor="#222222" Height="30px" VerticalAlign="Bottom" HorizontalAlign="Center" />
<RowStyle Height="50px" BackColor="#117186" />
<AlternatingRowStyle BackColor="#0b4d5b" />
</asp:GridView>
<div style="float:right; margin-bottom:20px; margin-right:20px"><input type="button" class="buttonEffect" value="Register New Address" /></div>
</div>
</div>
and here is my code behind.
retrievedata3ct rd3ct;
DataTable dt;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
rd3ct = new retrievedata3ct();
dt = new DataTable();
ds = new DataSet();
if (!this.IsPostBack)
{
addAddresses();
}
}
public void addAddresses()
{
rd3ct = new retrievedata3ct();
ds = new DataSet();
ds = rd3ct.addressesSelection("", "");
addressGrd.DataSource = ds.Tables[0];
addressGrd.DataBind();
addressGrd.Visible = true;
//ScriptManager.GetCurrent(this).RegisterPostBackControl(addressGrd);
}
public string Bind_Image(string Status)
{
bool status = Convert.ToBoolean(Status);
if (status)
{
return "adminCP/resources/images/icons/tick_circle.png";
}
else
{
return "adminCP/resources/images/icons/cross_circle.png";
}
}
protected void addressGrd_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
addressGrd.PageIndex = e.NewPageIndex;
addAddresses();
}
protected void Delete(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
string ds = "";
ds = rd3ct.addressesDeletion(lnkRemove.CommandArgument);
if (ds == "OK")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Record Deleted.');", true);
addAddresses();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error Occurred.');", true);
}
}
protected void Edit(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
Session["addressID"] = "";
Session["addressID"] = lnkRemove.CommandArgument;
Response.Redirect("editAddresses.php5", false);
}
protected void changeStatus(object sender, EventArgs e)
{
string ds = "";
ImageButton ib = (ImageButton)sender;
string[] commandArgs = ib.CommandArgument.ToString().Split(new char[] { ',' });
string status = commandArgs[0];
string id = commandArgs[1];
if (status == "True")
{
ds = rd3ct.addressesStatusUpdate(id, "False");
if (ds == "OK")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Status Disabled.');", true);
addAddresses();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error Occurred.');", true);
}
}
else
{
ds = rd3ct.addressesStatusUpdate(id, "True");
if (ds == "OK")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Status Enabled.');", true);
addAddresses();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error Occurred.');", true);
}
}
}
Please help me out. Any help would be highly appreciated.
Have you tried to create an empty master page to put the content into? I suspect your master page is breaking the GridView.
Problem Solved.
Actually button name was conflicting in grid view.
I was having a button and its ID was 'submit' and in my another page there was also a button named with the same ID. thats why gridview paging was not working.
R.I.P Coding.. :)
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" />
I'm trying to delete a row in a gridview (the data is not in the database yet), so it should be a simple delete row, if anybody can please point me in the right direction....
This is what I have done:
else if (e.CommandName == "DeletePart")
{
int index = Convert.ToInt32(e.CommandArgument); //#1 line
GridView1.DeleteRow(index); //#2 line
}
The error that I am receiving is : "Input string was not in a correct format." (this happens on #1 line)...
This is how the gridview looks like: (use a linkbutton to do the delete)
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
EmptyDataText="No parts has been added to the model, please add a part."
BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"
CellPadding="3" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="EditButton" runat="server" CssClass="EditButton" CommandName="Edit" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="DeleteButton" runat="server" CssClass="DeleteButton" CommandName="DeletePart" CommandArgument='<%# Container.DataItemIndex %>' Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FFFFCC" BorderColor="Black" BorderStyle="Solid"
BorderWidth="2px" />
</asp:GridView>
Class of how the gridview populated and binded:
public int companyID = 0;
public int methodID = 0;
DataTable dt;
#region SQLConnections
string connectionString = ConfigurationManager.ConnectionStrings["SOSConnectionString"].ConnectionString;
SqlConnection conn;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt = new DataTable();
MakeDataTable();
EmptyDataString();
}
else
{
dt = (DataTable)ViewState["DataTable"];
}
ViewState["DataTable"] = dt;
}
#region GridView
private void EmptyDataString()
{
TemplateBuilder tmpEmptyDataTemplate = new TemplateBuilder();
tmpEmptyDataTemplate.AppendLiteralString("No parts has been added to the model, please add a part.");
GridView1.EmptyDataTemplate = tmpEmptyDataTemplate;
GridView1.DataBind();
}
private void MakeDataTable()
{
dt.Columns.Add("Item");
dt.Columns.Add("Quantity");
dt.Columns.Add("Price P/Quantity");
}
private void AddToDataTable()
{
DataRow dr = dt.NewRow();
dr["Item"] = txtPart.Text;
dr["Quantity"] = numQuantity.Text;
dr["Price P/Quantity"] = txtPricePQ.Text;
dt.Rows.Add(dr);
}
private void BindGrid()
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnAddPart_Click(object sender, EventArgs e)
{
AddToDataTable();
BindGrid();
ClearNewParts();
}
#endregion
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
txtPart.Text = row.Cells[2].Text;
numQuantity.Text = row.Cells[3].Text;
txtPricePQ.Text = row.Cells[4].Text;
}
}
else if (e.CommandName == "DeletePart")
{
//int iCount = GridView1.Rows.Count;
//for (int i = 1; i <= iCount; i++)
//{
// GridView1.DeleteRow(i);
//}
// int rowIndex = Convert.ToInt32(GridView1.SelectedRow);
int index = Convert.ToInt32(e.CommandArgument);
GridView1.DeleteRow(index);
//int index = Convert.ToInt32(e.CommandArgument);
//GridView1.DeleteRow(rowIndex);
}
GridView1.DataBind();
}
Found the solution, only needed to do a databound.... Here is the working code:
else if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView1.DeleteRow(index);
((DataTable)ViewState["DataTable"]).Rows[index].Delete();
((DataTable)ViewState["DataTable"]).AcceptChanges();
GridView1.DataSource = (DataTable)ViewState["Data"];
GridView1.DataBind();
}
Seems like you didn't mention CommandArgument property in the GridView.
<asp:GridView runat="server" ID="gv"
CommandName="DeletePart"
CommandArgument='<%# Container.DataItemIndex %>'>
</asp:GridView>
Add the CommandArgument as shown above.
Try this..
In ASPX:
<asp:GridView runat="server" ID="Gridview1" CommandName="delete" CommandArgument='<%#Container.DataItem.Index %>'/>
Cs:
else if (e.CommandName == "DeletePart")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView1.DeleteRow(index);
}
try int.TryParse , this will solve the input string fromat problem , but why is it occuring that you need to check the CommandArgument you are setting.
else if (e.CommandName == "DeletePart")
{
int index =-1;
if(int.TryParse(e.CommandArgument,out index)) //#1 line
GridView1.DeleteRow(index); //#2 line
}
Thy This:)
<asp:GridView ID="GridView1" runat="server" CssClass="gridview"
HorizontalAlign="Left" PagerSettings-Visible="true" AllowPaging="True"
PageSize ="5" Width="300px" >
<Columns>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
then code behinde:
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
DirectCast(ViewState("CurrentDataReference"), DataTable).Rows.RemoveAt(e.RowIndex)
GridView1.DataSource = DirectCast(ViewState("CurrentDataReference"), DataTable)
GridView1.DataBind()
End Sub
I have a C# .Net application with a gridview within an Ajax Modal Popup (VS2008). I have the grid view set to return 10 records per page with paging enabled.
When the user clicks to change page within the gridview there is a postback which closes the modal window and then opens it again using ModalPopup.show();
Is there any way to avoid the postback of the whole page and just postback the gridview whilst keeping the modal window active? At the moment the postback of the whole page gives the impression of flicker...
<asp:Panel ID="Panel1" runat="server" Font-Italic="True"
Font-Names="Times New Roman" Font-Size="Small" ForeColor="#82B8DE">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
onpageindexchanging="GridView1_PageIndexChanging"
onrowdatabound="GridView1_RowDataBound"
onselectedindexchanged="GridView1_SelectedIndexChanged"
SelectedIndex="0" ShowHeader="False" Width="700px" ControlID="GridView1"
EventName="PageIndexChanging" Font-Italic="True" Font-Names="Times New Roman"
Font-Size="Medium">
<PagerSettings PageButtonCount="12" />
<RowStyle CssClass="RowStyle" BackColor="#EFF3FB" Font-Italic="True"
Font-Names="Times New Roman" Font-Size="Small" ForeColor="#82B8DE" />
<Columns>
<asp:BoundField DataField="Address" ReadOnly="True">
<ItemStyle Width="385px" />
</asp:BoundField>
<asp:BoundField DataField="XCoord" ReadOnly="True" ShowHeader="False" >
<ItemStyle CssClass="Hidden" />
</asp:BoundField>
<asp:BoundField DataField="YCoord" ReadOnly="True" ShowHeader="False" >
<ItemStyle CssClass="Hidden" />
</asp:BoundField>
</Columns>
<FooterStyle CssClass="FooterStyle" BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle CssClass="SelectedRowStyle" BackColor="#D1DDF1"
Font-Bold="True" ForeColor="#333333" />
<HeaderStyle CssClass="HeaderStyle" BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<EditRowStyle BackColor="#2461BF" Font-Italic="True"
Font-Names="Times New Roman" Font-Size="Medium" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</asp:Panel>
<ajax:ModalPopupExtender ID="ModalPopupExtender1" runat="server" PopupControlID="Panel1" TargetControlID="dummy"
BackgroundCssClass="ModalBackgroundGrid" BehaviorID="ModalGrid">
</ajax:ModalPopupExtender>
And the code behind...
public void Page_Load(object sender, EventArgs e)
{
try
{
if (!(Page.IsPostBack))
{
GridView1.EnableViewState = true;
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
GridView1.PagerSettings.Mode = PagerButtons.Numeric;
GridView1.Visible = true;
}
if (!m_bDisclaimerShown)
{
m_bDisclaimerShown = true;
mpe1.Show();
TabContainer.Visible = true;
ScaleBar1.Visible = true;
}
}
catch (Exception ex)
{
ShowMsg("Error - " + ex.Message);
}
}
protected void btnHide_Click(object sender, EventArgs e)
{
mpe1.Hide();
TabContainer.Visible = true;
ScaleBar1.Visible = true;
}
protected void cmdZoomAddress_Click(object sender, EventArgs e)
{
try
{
if (txtPostCode.Text.Length >= 7 && OpenDB())
{
string strPostcode = txtPostCode.Text;
strPostcode = strPostcode.Substring(0, 4) + strPostcode.Substring(strPostcode.Length - 3, 3);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = m_sqlConn;
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.CommandText = "sde.dbo.sp_selAddressByPostcode";
sqlCmd.Parameters.Add("#Postcode", SqlDbType.VarChar);
sqlCmd.Parameters["#Postcode"].Value = strPostcode;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd);
m_sqlDataTable = new DataTable();
sqlAdapter.Fill(m_sqlDataTable);
GridView1.DataSource = m_sqlDataTable;
GridView1.DataBind();
GridView1.Visible = true;
ModalPopupExtender1.Show();
}
else
{
ShowMsg("Error - No Postal Addresses Returned");
}
}
catch (Exception ex)
{
ShowMsg("Error - " + ex.Message);
}
finally
{
CloseDB();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
if (sender != null)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = m_sqlDataTable;
GridView1.DataBind();
ModalPopupExtender1.Show();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow GVRow = GridView1.SelectedRow;
int iX = (int)Convert.ToSingle(GVRow.Cells[1].Text);
int iY = (int)Convert.ToSingle(GVRow.Cells[2].Text);
GridView1.Visible = false;
MoveMap(iX, iY);
}
public void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex >= 0)
{
e.Row.Attributes["style"] = "cursor:pointer";
e.Row.Attributes.Add("onMouseOver", "this.style.cursor='hand';");
e.Row.Attributes.Add("onclick", ClientScript.GetPostBackEventReference(GridView1, "Select$" + e.Row.RowIndex.ToString()));
}
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
Page.ClientScript.RegisterForEventValidation(GridView1.UniqueID, "Select$" + r.RowIndex);
}
}
base.Render(writer);
}
thanks for your suggestion. I've put the gridview into a...
<asp:UpdatePanel>
<ContentTemplate>
The modal now stays however when I click a record in the grid view it doesn't close!