Delete a row in Gridview [duplicate] - c#

This question already has answers here:
How to delete row in gridview using rowdeleting event?
(16 answers)
Closed 8 years ago.
I want to delete a row using OnRowDeleting on GridView..
I have tried Different codes from internet but nothing works for me..
Help me Please!!
This is my code:
ASPX file::
<script type="text/c#" runat="server">
protected void BtnUpload_Click(object sender, EventArgs e)
{
if (Request.Files != null)
{
foreach (string file in Request.Files)
{
var uploadedFile = Request.Files[file];
if (uploadedFile.ContentLength > 0)
{
var appData = Server.MapPath("~/");
var fileName = Path.GetFileName(uploadedFile.FileName);
uploadedFile.SaveAs(Path.Combine(appData, fileName));
}
}
}
} //Some code here
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" CellPadding="4" ForeColor="#333333" GridLines="None" Width="155px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="Uploader" ButtonType="Button" Text="Upload" HeaderText="Upload" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" HeaderText="Delete" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Add New Row" OnClick="Button1_Click" />
<asp:Panel ID="pnlInfo" runat="server">
</asp:Panel>
<asp:LinkButton ID="BtnUpload" runat="server" Text="Upload" OnClick="BtnUpload_Click" />
//some code here
and this is ASPX.CS
public partial class WebForm4 : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs ea)
{
if(ea.CommandName=="Uploader")
{
//GridViewRow grv = (GridViewRow);
int i = Convert.ToInt32(ea.CommandArgument);
FileUpload fileUpload = GridView1.Rows[i].FindControl("FileUpload1") as FileUpload;
if (fileUpload.HasFile)
{
try
{
string filename = Path.GetFileName(fileUpload.FileName);
fileUpload.SaveAs(Server.MapPath("~/") + filename);
}
catch (Exception ex)
{
String se = ex.Message;
}
}
}
}
protected virtual void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs ea)
{
//Suggest Code Here..
}
private void AddNewRow()
{
dt = new DataTable();
dt.Columns.Add("sno");
dt.Columns.Add("name");
foreach (GridViewRow gvRow in GridView1.Rows)
{
DataRow dr = dt.NewRow();
//dr["sno"] = ((Label)gvRow.FindControl("lblSno")).Text;
//dr["name"] = ((Label)gvRow.FindControl("txtName")).Text;
dt.Rows.Add(dr);
}
DataRow dr1 = dt.NewRow();
dr1["sno"] = "";
dr1["name"] = "";
dt.Rows.Add(dr1);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
AddNewRow();
}
}
}
Please Help...

I'd recommend you to work with the bound data while adding/deleting rows, not with the rows directly since you've chosen grid view. Code is much simpler then.
Below is an example - note that I initialize there DataTable in a static scope (which is not a perfect place) - store it where you need - in memory/session, or in view state - depends on your task there.
public partial class WebForm4 : System.Web.UI.Page
{
private static DataTable MyDataTable = new DataTable();
static WebForm4()
{
MyDataTable.Columns.Add("sno");
MyDataTable.Columns.Add("name");
}
private void AddNewRow()
{
MyDataTable.Rows.Add(MyDataTable.NewRow());
GridView1.DataSource = MyDataTable;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
AddNewRow();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
MyDataTable.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = MyDataTable;
GridView1.DataBind();
}
}
Hope that helped.

Related

Gridview Paging is not working when i use it in content place holder?

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.. :)

display in textbox when checkbox is checked in gridview

i have a checkbox in a gridview , i want to display row's data in textbox when i check o checkbox .this is my buttun's code :
protected void ButtonModifEnfant_Click(object sender, EventArgs e)
{
#region
try
{
int nbr_check = 0;
string myid = "";
for (int i = 0; i < gv_enfant.Rows.Count; i++)
{
CheckBox check = (CheckBox)gv_enfant.Rows[i].Cells[0].FindControl("CheckBoxenfant");
if (check.Checked)
{
myid = ((HiddenField)gv_enfant.Rows[i].Cells[0].FindControl("codeenfant")).Value;
//ButtonModifEnfant.Enabled = true;
//ButtonSuppEnfant.Enabled = true;
//myid = gv_enfant.Rows[i].Cells[0].Text;
//nbr_check++;
}
else
{
//ButtonModifEnfant.Enabled = false;
//ButtonSuppEnfant.Enabled = true;
}
}
if (nbr_check >= 1)
{
//ButtonModifEnfant.Enabled = true;
Response.Write("<script>alert ('Error!')</script>");
return;
}
else if (nbr_check == 1)
{
//ButtonModifEnfant.Enabled = true;
}
ModalPopupExtenderModifierEnfant.Show();
c.cmd = c.cn.CreateCommand();
c.cmd.CommandText = "select prenom , DateNaissance , Scolarise , Activite from Enfants where codeEnfants = " + myid;
if (c.cn.State == ConnectionState.Closed)
{
c.cn.Open();
}
SqlDataReader read = c.cmd.ExecuteReader();
if (read.HasRows)
{
read.Read();
TextBox_NPmodif.Text = read[0].ToString();
TextBox_DNmodif.Text = read[1].ToString();
TextBox_Scolarisemodif.Text = read[2].ToString();
TextBox_Activitemodif.Text = read[3].ToString();
}
read.Close();
//gv_enfant.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (c.cn.State == ConnectionState.Open)
{
c.cn.Close();
}
}
#endregion
}
and this is my checkbox code :
protected void CheckBoxEnfants_CheckedChanged(object sender, EventArgs e)
{
int chek = 0;
for (int i = 0; i < gv_enfant.Rows.Count; i++)
{
CheckBox chbox = (CheckBox)gv_enfant.Rows[i].Cells[0].FindControl("CheckBoxenfant");
if (chbox.Checked)
{
chek++;
}
}
if (chek != 1)
{
ButtonModifEnfant.Enabled = false;
ButtonSuppEnfant.Enabled = false;
}
else
{
ButtonModifEnfant.Enabled = true;
ButtonSuppEnfant.Enabled = true;
}
}
and for the html code of gridview :
<asp:GridView ID="gv_enfant" runat="server" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1"
Width="533px">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxenfant" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBoxEnfants_CheckedChanged" />
<asp:HiddenField ID="codeenfant" runat="server" Value='<%# Eval("codeEnfants") %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="prenom" HeaderText="prenom" SortExpression="prenom" />
<asp:BoundField DataField="DateNaissance" HeaderText="Date Naissance" DataFormatString="{0:d}"
SortExpression="DateNaissance" />
<asp:BoundField DataField="Scolarise" HeaderText="Scolarise" SortExpression="Scolarise" />
<asp:BoundField DataField="Activite" HeaderText="Activite" SortExpression="Activite" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CVtechConnectionString10 %>"
SelectCommand="SELECT * FROM [Enfants] WHERE ([ppr] = #ppr)">
<SelectParameters>
<asp:SessionParameter Name="ppr" SessionField="code" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
Thank you
This may help you.
if (check.Checked)
{
txtBox.Text=gv_enfant["yourColumnName",i].Value.ToString();
}
try it,
Front-End
<asp:CheckBox ID="CheckBoxenfant" runat="server" index="<%# Container.DataItemIndex %>" AutoPostBack="true" OnCheckedChanged="CheckBoxEnfants_CheckedChanged" />
<asp:TextBox ID="textbx" runat="server" Enabled="false" Text='<%# Eval("codeEnfants") %>' />
Code-behind
protected void CheckBoxEnfants_CheckedChanged(object s, EventArgs e)
{
byte index = byte.Parse((s as CheckBox).Attributes["index"]);
(gv_enfant.Rows[index].FindControl("textbx") as TextBox).Enabled = (gv_enfant.Rows[index].FindControl("CheckBoxenfant") as CheckBox).Checked;
}

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" />

Can't get value from radio button on gridview on C#

Hello i have a Gridview with 4 radio buttons and i want to get the value from them, and no matter what i do the value is always false, could someone tellme where is my mistake?
This is the code of the gridview:
<asp:GridView ID="GridView8" runat="server" Width="903px"
Height="516px" CellPadding="4" ForeColor="#333333" GridLines="None"
Visible="False"
>
<AlternatingRowStyle BorderColor="Black" BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Solicitante/">
<ItemTemplate>
<asp:RadioButton ID="optCl1" runat="server" Text="SI" GroupName="optCl" />
<asp:RadioButton ID="optCl2" runat="server" Text="NO" GroupName="optCl" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CoGarante">
<ItemTemplate >
<asp:RadioButton ID="optGar1" runat="server" Text="SI" GroupName="optGar" />
<asp:RadioButton ID="optGar2" runat="server" Text="NO" GroupName="optGar" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BorderColor="Black" />
<FooterStyle BackColor="#990000" BorderColor="Black" ForeColor="White"
Font-Bold="True" />
<HeaderStyle BackColor="#990000" BorderColor="Black" Font-Bold="True"
ForeColor="White" />
<PagerStyle ForeColor="#333333" HorizontalAlign="Center" BackColor="#FFCC66" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
The code of the function that read the radiobutton
protected void saveQuestions()
{
foreach (GridViewRow row in GridView8.Rows)
{
RadioButton rb = row.Cells[2].FindControl("optGar2") as RadioButton;
Response.Write(rb.Checked);
}
conn.Close();
}
The code of the function that set the data on the gridview:
protected void loadQuestions()
{
OdbcConnection conn = connection();
conn.Open();
OdbcCommand findSql = new OdbcCommand("SELECT question AS PREGUNTAS,id FROM questionary_reg WHERE(status='1')", conn);
GridView8.DataSource = null;
DataTable dt = new DataTable();
dt.Load(findSql.ExecuteReader());
GridView8.DataSource = dt;
GridView8.DataBind();
conn.Close();
}
The problem because happen postback and reset the values inside the gridview, make sure you
call this function loadQuestions() on if !Postback ONLY
if(!IsPostBack){
loadQuestions();
}
#UPDATE 1 WORKING CODE :
//Design
<asp:GridView runat="server" ID="gv">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton runat="server" ID="rd" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" ID="btn" onclick="btn_Click" />
//Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStringDb1"].ToString()))
{
try
{
String cmdText = "SELECT * FROM Image WHERE IsDeleted=#isDeleted";
SqlCommand cmd = new SqlCommand(cmdText, cn);
cmd.Parameters.AddWithValue("#IsDeleted", "false");
cn.Open();
SqlDataAdapter myAdapter = new SqlDataAdapter(cmd);
DataTable dt_Category = new DataTable();
myAdapter.Fill(dt_Category);
cn.Close();
gv.DataSource = dt_Category;
gv.DataBind();
}
catch (Exception ex)
{
}
}
}
}
protected void btn_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gv.Rows)
{
RadioButton rd = (RadioButton)gvr.FindControl("rd");
if (rd.Checked)
{
}
else
{
}
}
}
Maybe you need a 'CheckedChanged' event: (Tested and working)
In ASPX set (in this example, you can to see label display the number of row selected)
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rbtnSelect" AutoPostBack="true" runat="server" OnCheckedChanged="rbtnSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
and code-behing set
protected void rbtnSelect_CheckedChanged(object sender, EventArgs e)
{
RadioButton selectButton = (RadioButton)sender;
GridViewRow row = (GridViewRow)selectButton.Parent.Parent;
int a = row.RowIndex;
foreach (GridViewRow rw in gvCursos.Rows)
{
if (selectButton.Checked)
{
if (rw.RowIndex != a)
{
lbResultado.Text = rw.RowIndex.ToString();
RadioButton rd = rw.FindControl("rbtnSelect") as RadioButton;
rd.Checked = false;
}
}
}
}
Change this:
RadioButton rb = row.Cells[2].FindControl("optGar2") as RadioButton;
To this:
RadioButton rb = row.FindControl("optGar2") as RadioButton;
for (int i = 0; i < GridView8.Rows.Count; i++)
{
if (GridView8.Rows[i].RowType == DataControlRowType.DataRow)
{
RadioButton rb= (RadioButton)grdView.Rows[i].FindControl("optGar2");
Response.Write(rb.Checked);
}
}
foreach (GridViewRow gvp in gridView1.Rows)
{
System.Web.UI.HtmlControls.HtmlInputRadioButton rd = (System.Web.UI.HtmlControls.HtmlInputRadioButton)gvp.FindControl("rd");
if (rd.Checked)
{
string s = rd.Value;
}
else
{
}
}
design view
<ItemTemplate>
<input runat="server" id='rd' type="radio" value='<%# Eval("id") %>' onclick="javascript:SelectSingleRadiobutton(this.id)" />
</ItemTemplate>

Gridview in Modal Popup Extender- Postback Issues?

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!

Categories