I am working in a ASP.NET project in an empty web application in C# and I have made a gridview with CRUD operations. But when I execute my project and click on the buttons I have made it takes me to the first row and I then have to scroll back down again. It is really annoying but I do not know why it does that. Even though I have used MaintainScrollPositionOnPostBack="true" it does not work. Is there anything I cad add to my code or something I have to be aware of?
Default.aspx
<%# Page Language="C#" MaintainScrollPositionOnPostBack="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestUsers.Default" %>
<link href="TestUsers.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
<link rel="stylesheet" href="TestUsers.css">
<link rel="shortcut icon" type="image/x-icon" href="~/orbitone.ico" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ESDTESTERS</title>
<%-- <meta http-equiv="refresh" content="20">--%>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<br /><br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Sing Out" />
<br /><br />
<asp:TextBox ID="TextBox1" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" Width="100px" />
<br />
</div>
<asp:GridView ID="gvTestUsers" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="tbl_users_key" ShowHeaderWhenEmpty="True" OnRowCommand="gvTestUsers_RowCommand" OnRowEditing="gvTestUsers_RowEditing" OnRowCancelingEdit="gvTestUsers_RowCancelingEdit"
OnRowDeleting="gvTestUsers_RowDeleting" OnRowUpdating="gvTestUsers_RowUpdating" HorizontalAlign="Center" OnPageIndexChanging="gvTestUsers_PageIndexChanged"
BackColor="#CCCCCC" BorderColor="#000000" BorderStyle="Solid" BorderWidth="3px" CellPadding="5" Width="1300px" CellSpacing="2" ForeColor="Black" PageSize="15" AllowPaging="True" >
<%--Theme Properties--%>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" Font-Size="Large" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
<Columns>
<asp:TemplateField HeaderText="tbl_users_key">
<ItemTemplate>
<asp:Label Text='<%# Eval("tbl_users_key") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtID" Text='<%# Eval("tbl_users_key") %>' runat="server" ReadOnly="true" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label Text='<%# Eval("Name") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" ReadOnly="True" Text='<%# Eval("Name") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNamefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CostCenter">
<ItemTemplate>
<asp:Label Text='<%# Eval("CostCenter") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCostCenter" ReadOnly="True" Text='<%# Eval("CostCenter") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCostCenterfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:Label Text='<%# Eval("Employee") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployee" ReadOnly="True" Text='<%# Eval("Employee") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FootPlate">
<ItemTemplate>
<asp:Label Text='<%# Eval("FootPlate") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFootPlate" Text='<%# Eval("FootPlate") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFootPlatefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="WirstCord">
<ItemTemplate>
<asp:Label Text='<%# Eval("WirstCord") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtWirstCord" Text='<%# Eval("WirstCord") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtWirstCordfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Excluded">
<ItemTemplate>
<asp:Label Text='<%# Eval("Excluded") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExcluded" Text='<%# Eval("Excluded") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExcludedfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:Label Text='<%# Eval("Comment") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtComment" Text='<%# Eval("Comment") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCommentfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/delete.png" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" ToolTip="Delete" Width="20px" Height="20px" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="~/GridImages/add.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<asp:Label ID="lblSuccessMessage" Text="" runat="server" ForeColor="Green" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
<br />
<asp:Label ID="lblErrorMessage" Text="" runat="server" ForeColor="Red" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
</div>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace TestUsers
{
public partial class Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGridView();
}
}
void PopulateGridView()
{
DataTable dtbl = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("Select * FROM TBL_USERS", sqlCon);
sqlDa.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
}
else
{
dtbl.Rows.Add(dtbl.NewRow());
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
gvTestUsers.Rows[0].Cells.Clear();
gvTestUsers.Rows[0].Cells.Add(new TableCell());
gvTestUsers.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count;
gvTestUsers.Rows[0].Cells[0].Text = "No Data Found.";
gvTestUsers.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
protected void gvTestUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("AddNew"))
{
int tbl_users_key = 0;
TextBox myTxt;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtNamefooter"));
string Name;
Name = myTxt.Text;
string CostCenter;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCostCenterfooter"));
CostCenter = myTxt.Text;
string Employee;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtEmployeefooter"));
Employee = myTxt.Text;
Boolean FootPlate;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtFootPlatefooter"));
FootPlate = Convert.ToBoolean(myTxt.Text);
Boolean WirstCord;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtWirstCordfooter"));
WirstCord = Convert.ToBoolean(myTxt.Text);
Boolean Excluded;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtExcludedfooter"));
Excluded = Convert.ToBoolean(myTxt.Text);
string Comment;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCommentfooter"));
Comment = myTxt.Text;
string sMsg;
sMsg = "";
bool btest = fcEditTBL_USERS(tbl_users_key, Name, CostCenter, Employee, FootPlate, WirstCord, Excluded, Comment, ref sMsg,0);
if (btest == false)
{
lblErrorMessage.Text = sMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = Name + " Was Added To Record.";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvTestUsers.EditIndex = e.NewEditIndex;
PopulateGridView();
}
protected void gvTestUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvTestUsers.EditIndex = -1;
PopulateGridView();
}
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, Convert.ToBoolean(dltFootPlate), Convert.ToBoolean(dltWirstCord), Convert.ToBoolean(dltExcluded), dltComment,ref dltsMsg,2);
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
gvTestUsers.EditIndex = -1;
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
public bool fcEditTBL_USERS
(int tbl_users_key, string Name, string CostCenter, string Employee, bool FootPlate, bool WirstCord, bool Excluded, string Comment, ref string sMsg, int iMode)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
try
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spEditTBL_USERS", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter returnParameter = sqlCmd.Parameters.Add(new SqlParameter("#RETURN_VALUE", DbType.Int32));
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCmd.Parameters.Add("#ID", SqlDbType.Int).Value=tbl_users_key ;
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value=Name;
sqlCmd.Parameters.Add("#CostCenter", SqlDbType.VarChar, 10).Value=CostCenter;
sqlCmd.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value=Employee;
sqlCmd.Parameters.Add("#FootPlate", SqlDbType.Bit).Value=FootPlate;
sqlCmd.Parameters.Add("#WirstCord", SqlDbType.Bit).Value=WirstCord;
sqlCmd.Parameters.Add("#Excluded", SqlDbType.Bit).Value=Excluded;
sqlCmd.Parameters.Add("#Comment", SqlDbType.VarChar, 255).Value=Comment;
sqlCmd.Parameters.Add("#MODE", SqlDbType.SmallInt).Value =iMode;
sqlCmd.Parameters.Add("#MSG", SqlDbType.NVarChar, 255).Value=sMsg;
sqlCmd.Parameters["#MSG"].Direction = ParameterDirection.Output;
sqlCmd.ExecuteNonQuery();
sMsg = sqlCmd.Parameters["#MSG"].Value.ToString();
int rtn = (int)sqlCmd.Parameters["#RETURN_VALUE"].Value;
if (rtn != 0)
{
return false;
}
sqlCmd.Dispose();
return true;
}
finally
{
}
}
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, Convert.ToBoolean(tmpFootPlate), Convert.ToBoolean(tmpWirstCord), Convert.ToBoolean(tmpExcluded), tmpComment,ref tmpsMsg,1);
//Reload Page
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_PageIndexChanged(object sender, GridViewPageEventArgs e)
{
gvTestUsers.PageIndex = e.NewPageIndex;
PopulateGridView();
}
protected void Button1_Click(object sender, EventArgs e)
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand (find,con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("LoginForm.aspx");
}
}
}
Thank you for the explanation. Please try setting gridview editindex before populating the gridview (after updating and deleting ) Hope this helps.
Working below code for me.
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, tmpFootPlate, tmpWirstCord, tmpExcluded, tmpComment, ref tmpsMsg, "Update");
//add this
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
And the row deleting below,
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, dltFootPlate, dltWirstCord,dltExcluded, dltComment, ref dltsMsg, "Delete");
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
I solved it by moving the SearchBox-Event code into my PopulateGridView.
So now the PopulateGridView looks like this:
void PopulateGridView()
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
And the Searchbox-Event:
protected void Button1_Click(object sender, EventArgs e)
{
PopulateGridView();
}
Else it would jump straight to Void PopulateGridView each time I would try to use an EDIT,CREATE or DELETE operation.
Im beginner for the ASP.NET ,Im develop the File Upload in Grid View with Ajax Modal Popup its working i can upload image and i can see uploaded image in uploaded folder, but i cant make uploaded image Path to grid view, can you please help me.
ASPX
<asp:UpdatePanel ID="UpdatePanelArt" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="table-responsive col-sm-12">
<asp:GridView ID="gvArticle" ShowHeaderWhenEmpty="True" ClientIDMode="AutoID" CssClass="table table-bordered table-condensed table-hover" AutoGenerateColumns="False" runat="server" AllowPaging="True" PageSize="15" OnRowDataBound="gvArticle_RowDataBound" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" OnRowUpdating="gvArticle_RowUpdating">
<%--<HeaderStyle BackColor="#3d4247" ForeColor="White" />--%>
<Columns>
<asp:TemplateField HeaderText="intArticleDetail" Visible="false">
<ItemTemplate>
<asp:Label ID="lblArticleDetailId" Width="2" Text='<%# Bind("intArticleDetailId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SectionID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblSectionId" Width="2" Text='<%# Bind("intSectionId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Section">
<ItemTemplate>
<asp:Label ID="lblSectionName" Width="100" Text='<%# Bind("strSectionName") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Compound">
<EditItemTemplate>
<asp:Label ID="lblItemTypeEdit" Width="50" Text='<%# Bind("strCompoundName") %>' lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlCompoundId" Width="200" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemTemplate>
<asp:TextBox ID="txtdecSectionWeighte" Width="100%" Text='<%# Bind("decSectionWeight") %>' lientIDMode="Static" runat="server"> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:TemplateField HeaderText="Messagers">
<ItemTemplate>
<asp:TextBox ID="txtMessage" Width="100%" Text='<%# Bind("intMessageId") %>' ClientIDMode="Static" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Messagers">
<EditItemTemplate>
<asp:Label ID="lblMessageId" Width="50" Text='<%# Bind("strMessage") %>' ClientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlMessage" Width="300" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<ItemTemplate>
<asp:Label ID="FilePath" Width="2" runat="server"></asp:Label>
</ItemTemplate>
<asp:TemplateField HeaderText="Images">
<ItemTemplate>
<%-- <asp:Image ID="Image1" ImageUrl='<%# Eval("StrImage") %>' runat="server" Height="100" />--%>
<%-- <asp:FileUpload runat="server" AutoPostBack="True" ID="uploadFImage" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>--%>
<asp:LinkButton ID="lnkUpload" runat="server" Text="Upload Resume" ></asp:LinkButton>
<%--Using ModalPopupExtender--%>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="lnkUpload"
PopupControlID="pnlUpload" BackgroundCssClass="ModalPopupBG" CancelControlID="btnCancel">
</asp:ModalPopupExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="btnViewFImage" Width="40" Height="40"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="gvArticle"/>
</Triggers>
</asp:UpdatePanel>
</div>
</div><asp:Panel ID="pnlUpload" runat="server" Width="450px" BackColor="#E39A19"
BorderColor="#C3680D" BorderStyle="Solid">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table style="width: 450px; margin: 0 auto">
<tr>
<td align="right" style="background-image: url('backTable.PNG')">
</td>
</tr>
<tr>
<td align="left">
<asp:FileUpload ID="flp_Resume" runat="server" Width="222px" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server"
ControlToValidate="flp_Resume" ErrorMessage="*"
ToolTip="Please Select a File to Upload."></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator5" runat="server"
ControlToValidate="flp_Resume" ErrorMessage="*"
ToolTip="Only txt,doc or docx files are Allowed"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+((.pdf)|(.doc)|(.txt)|(.docx))$"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="left">
<asp:Button ID="btnUpload" runat="server" Text="Upload" Width="80px"
onclick="btnUpload_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" Width="80px" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblError" runat="server" Font-Bold="True" Font-Names="Georgia"
ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload"/>
</Triggers>
cs
#region Detail Save1
private DataTable CreateDetailSave()
{
DataTable dtDetailSave1 = new DataTable();
DataColumn dc1;
dc1 = new DataColumn("intArticleDetailId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intSectionId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intCompoundId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("decSectionWeight");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intMessageId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("uploadFImage");
dtDetailSave1.Columns.Add(dc1);
foreach (GridViewRow row in gvArticle.Rows)
{
DataRow dr = dtDetailSave1.NewRow();
Label lblintArticleDetailId = (Label)row.FindControl("lblArticleDetailId");
Label lblSectionId = (Label)row.FindControl("lblSectionId");
DropDownList ddlCompound = (DropDownList)row.FindControl("ddlCompoundId");
TextBox txtdecSectionWeighte = (TextBox)row.FindControl("txtdecSectionWeighte");
DropDownList intMessage = (DropDownList)row.FindControl("ddlMessage");
FileUpload uploadFImage = (FileUpload)row.FindControl("uploadFImage");
dr["intArticleDetailId"] = CurrentMode == "Add" ? -1 : Convert.ToInt32(lblintArticleDetailId.Text);
dr["intSectionId"] = Convert.ToInt32(lblSectionId.Text);
dr["intCompoundId"] = ddlCompound.SelectedValue;
dr["decSectionWeight"] = txtdecSectionWeighte.Text.Trim() != "" ? Convert.ToDecimal(txtdecSectionWeighte.Text.Trim()) : 0;
dr["intMessageId"] = intMessage.SelectedValue;
dr["uploadFImage"] = uploadFImage.HasFile;
dtDetailSave1.Rows.Add(dr);
}
return dtDetailSave1;
}
#endregion
#region Save
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
if (FSaveConfirmation() == true)
{
string strArticleNo;
int intStatus = 8;
if (CurrentMode == "Add")
{
strArticleNo = "aaaaaaaa";
}
else
{
strArticleNo = txtArticleNo.Text.ToString();
}
DataTable dtDetailSave1 = CreateDetailSave();
string PageName = Path.GetFileNameWithoutExtension(Page.AppRelativeVirtualPath);
string Saved = clsArticle.saveArticleData(SelectedArticleId, strArticleNo, txtArticleDescription.Text.ToString(), txtRemarks.Text.ToString(), intStatus, 1, CurrentMode,
PageName, 16, dtDetailSave1);
if (Saved != "Error")
{
lblMsg.ForeColor = System.Drawing.Color.Green;
if (CurrentMode == "Add")
{
lblMsg.Text = "Record Saved Successfully";
txtArticleNo.Text = Saved.ToString();
}
else if (CurrentMode == "Modify")
{
lblMsg.Text = "Record Updated Successfully";
}
else if (CurrentMode == "Delete")
{
lblMsg.Text = "Record Deleted Successfully";
}
else if (CurrentMode == "Confirm")
{
lblMsg.Text = "Record Confirmed Successfully";
}
btnClear.Enabled = true;
btnSave.Enabled = true;
}
else if (Saved == "Error")
{
lblMsg.Text = "Article Saving Error";
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Save Confirmation
private bool FSaveConfirmation()
{
lblMsg.ForeColor = System.Drawing.Color.Red;
Boolean blnSaveCon = true;
//if (CurrentMode == "Add")
//{
if (txtArticleDescription.Text.ToString() == "")
{
lblMsg.Text = "Enter Article Description";
blnSaveCon = false;
goto end;
}
//}
end: { }
return blnSaveCon;
}
#endregion
#region Get controls in page
private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection) where T : Control
{
foreach (Control control in controlCollection)
{
if (control is T)
resultCollection.Add((T)control);
if (control.HasControls())
GetControlList(control.Controls, resultCollection);
}
}
#endregion
#region pageload
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ClearControls();
FillArticleDetails();
EnableControls(false);
Session["SearchPopup"] = false;
}
else
{
if (Session["SearchPopup"] != null)
{
SearchPopup = (bool)(Session["SearchPopup"]);
if (SearchPopup != false)
{
MyMPE.Show();
}
else
{
MyMPE.Hide();
}
}
vAdSearchParaList = new List<SearchParametors>();
}
}
#endregion
#region Advance Search
protected void btnAdSearchClose(object sender, ImageClickEventArgs e)
{
Session["SearchPopup"] = false;
Session["sSearchddlList"] = null;
GridView dtgResult = (GridView)ucDesignation.FindControl("ucgrdSearchConditions");
dtgResult.DataSource = null;
dtgResult.DataBind();
dtgAdSearchResult.DataSource = null;
dtgAdSearchResult.DataBind();
MyMPE.Hide();
}
#region Create Article table
private void createArticleDataTable()
{
if (dt.Columns.Count == 0)
{
dt.Columns.Add(new DataColumn("intArticleDetailId", typeof(int)));
dt.Columns.Add(new DataColumn("intSectionId", typeof(int)));
dt.Columns.Add(new DataColumn("strSectionName", typeof(string)));
dt.Columns.Add(new DataColumn("intCompoundId", typeof(string)));
dt.Columns.Add(new DataColumn("decSectionWeight", typeof(string)));
dt.Columns.Add(new DataColumn("intMessageId", typeof(string)));
dt.Columns.Add(new DataColumn("uploadFImage", typeof(string)));
}
gvArticle.DataSource = dt;
gvArticle.DataBind();
}
#endregion
#region Compound Grid - Add empty row
private void ArticleGridAddEmptyRow(int newId)
{
DataRow newDr = null;
newDr = dt.NewRow();
newDr["intArticleDetailId"] = 1;
newDr["intSectionId"] = 1;
newDr["strSectionName"] = "";
newDr["intCompoundId"] = "";
newDr["decSectionWeight"] = "";
newDr["intMessageId"] = "";
newDr["strImage"] = "";
dt.Rows.Add(newDr);
if (dtArticleDetails == null || dtArticleDetails.Rows.Count == 0)
{
dtArticleDetails = dt;
}
else
{
dtArticleDetails.Merge(dt);
gvArticle.DataSource = dt;
gvArticle.DataBind();
}
}
#endregion
private void FillArticleDetails()
{
DataSet dtCompoundData = clsArticle.GeArticleDetailData(SelectedArticleId);
if (dtCompoundData.Tables[0].Rows.Count > 0)
{
createArticleDataTable();
dt = dtCompoundData.Tables[0];
dtArticleDetails = dt;
gvArticle.DataSource = dtArticleDetails;
gvArticle.DataBind();
}
else
{
lblMsg.Text = "No Records Found";
}
}
protected void gvArticle_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
{
}
DataTable CompoundCode = clsArticle.CompoundDataForGrid("");
DropDownList ddlCompoundId = (DropDownList)e.Row.FindControl("ddlCompoundId");
if (ddlCompoundId != null)
{
ddlCompoundId.DataTextField = "Compound Code";
ddlCompoundId.DataValueField = "Compound Id";
ddlCompoundId.DataSource = CompoundCode;
ddlCompoundId.DataBind();
string country = (e.Row.FindControl("ddlCompoundId") as DropDownList).Text;
ddlCompoundId.Items.FindByValue(country).Selected = true;
}
DataTable MsgCode = clsArticle.MessageDataForGrid("");
DropDownList ddlMessage = (DropDownList)e.Row.FindControl("ddlMessage");
if (ddlMessage != null)
{
ddlMessage.DataTextField = "Message Name";
ddlMessage.DataValueField = "Message Id";
ddlMessage.DataSource = MsgCode;
ddlMessage.DataBind();
ddlMessage.Items.Insert(0, new ListItem("Please select"));
string country = (e.Row.FindControl("ddlMessage") as DropDownList).Text;
ddlMessage.Items.FindByValue(country).Selected = true;
}
//}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (flp_Resume.HasFile)
{
string fileName = Path.GetFileName(flp_Resume.PostedFile.FileName);
string fullpath = Path.GetFullPath(flp_Resume.PostedFile.FileName);
flp_Resume.PostedFile.SaveAs(Server.MapPath("~/Uploaded Images/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
else
{
lblError.Text = "Please Select a File";
return;
}
}
I have a nested gridiview inside a repeater :
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SDSRepeaterCity" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<table>
<tr>
<td ><label style="color:black; font-size:20px;"><%#Eval("nome_citta") %></label></td>
<td style="display:none;"><asp:Label ID="lblIdCity" runat="server" Text='<%#Eval("id_citta") %>' ></asp:Label></td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="False"
CssClass="Grid"
EmptyDataText="Nessun risultato corrispondono alla sua ricerca"
ShowHeaderWhenEmpty="True" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="../../../Images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="TipoServizio" HeaderText="TipoServizio" />
<asp:BoundField ItemStyle-Width="33%" DataField="Tipologia" HeaderText="Tipologia" />
<asp:TemplateField>
<HeaderTemplate>Prezzo di base</HeaderTemplate>
<ItemTemplate >
<asp:TextBox ID="TBPrezzo" style="text-align:center;font-size:14px;" runat="server" Text=""></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
<HeaderStyle Width="150px" />
</asp:TemplateField>
<asp:BoundField DataField="tipo_macchina" ItemStyle-CssClass="hide" HeaderStyle-CssClass="hide" HeaderText="AutoMezzo">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="tipo_macchina" HeaderText="AutoMezzo">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblGvIdCity" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
And a button update with the following code:
TraifRegBLL trigis = TraifRegBLL.Instance;
string strConnString1 = "connexion";
using (SqlConnection con = new SqlConnection(strConnString1))
{
using (SqlCommand cmd = new SqlCommand())
{
String id_aff = Session["id_affiliato"].ToString();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM TarifSMReg WHERE id_affiliato= #Codice ";
cmd.Parameters.AddWithValue("#Codice", id_aff);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
//Add new inseriment
for (int i = 0; i < Repeater1.Items.Count; i++)
{
GridView gvCustomers = Repeater1.Items[i].FindControl("gvCustomers") as GridView;
for (int j = 0; j < gvCustomers.Rows.Count; j++)
{
Label lblGvIdCity = gvCustomers.Rows[j].FindControl("lblGvIdCity") as Label;
GridView gvOrders = gvCustomers.Rows[j].FindControl("gvOrders") as GridView;
for (int k = 0; k < gvOrders.Rows.Count; k++)
{
TextBox TBPrezzo = gvOrders.Rows[k].FindControl("TBPrezzo") as TextBox;
if (String.IsNullOrEmpty(TBPrezzo.Text)==true) { TBPrezzo.Text = "0"; }
if (Convert.ToDouble(TBPrezzo.Text) > 0)
{
TarifSMReg t = new TarifSMReg();
t.id_citta = lblGvIdCity.Text;
t.id_affiliato = Session["id_affiliato"].ToString();
t.tipologia_macchina = gvCustomers.Rows[j].Cells[2].Text;
t.TipoServizio = gvOrders.Rows[k].Cells[0].Text;
t.Tipologia = gvOrders.Rows[k].Cells[1].Text;
t.PrezzoBaseRG = Convert.ToDouble(TBPrezzo.Text.Replace(",", "."));
trigis.addTarifReg(t);
}
}
}
}
here is the result if i insert the price the first time:
but if i update the price will be duplicated like
this.
Can anyone explain me why?
thank you
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;
}
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>