In below datalist represents set of question's and answer.
How to insert the user selected right answer radio button value into database when the user clicks on Final submit button?
<asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" onselectedindexchanged="rd_CS_CheckedChanged">
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<ItemTemplate>
Q:
<asp:Label ID="QLabel" runat="server" Text='<%# Eval("Q") %>' />
<br />
A:
<asp:RadioButton ID="rd_CS" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("A") %>'></asp:RadioButton>
<br />
B:
<asp:RadioButton ID="rd_CS2" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("B") %>'></asp:RadioButton>
<br />
C:
<asp:RadioButton ID="rd_CS3" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("C") %>'></asp:RadioButton>
<br />
D:
<asp:RadioButton ID="rd_CS4" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("D") %>'></asp:RadioButton>
<p style="color: #FF3300">
<asp:Label ID="Correct_AnswerLabel" runat="server"
Text='<%# Eval("Correct_Answer") %>' Visible="False" /></p>
</ItemTemplate>
<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:DataList>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/Quize.mdb"
SelectCommand="SELECT [Q],[A], [B], [C], [D], [Correct Answer] AS Correct_Answer FROM [QuizData]">
</asp:AccessDataSource>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
In Button1_Click on your codebehind you can improve this method:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
RadioButton rd_CS = (RadioButton)item.FindControl("rd_CS");
RadioButton rd_CS2 = (RadioButton)item.FindControl("rd_CS2");
RadioButton rd_CS3 = (RadioButton)item.FindControl("rd_CS3");
RadioButton rd_CS4 = (RadioButton)item.FindControl("rd_CS4");
if (rd_CS.Checked)
{
Insert(rd_CS.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS2.Checked)
{
Insert(rd_CS2.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS3.Checked)
{
Insert(rd_CS3.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS4.Checked)
{
Insert(rd_CS4.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
}
}
And the Insert function definition will be same as:
private void Insert(string value)
{
//Your code here to save on database
OleDbConnection connection = new OleDbCommand("Your sql connection String");
OleDbCommand command = new OleDbCommand("Your sql insert query");
command.Connection = connection;
//Parámeters of command
OleDbParameter param = new OleDbParameter("Parameter name and next your type", OleDbType.VarChar);
param.Value = value;
command.Parameters.Add(param);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
//Your value is saved now
}
This is how you can save all checked radiobutton on datalist you asked
This is my codebehind .When i click on button then Repeated selected radio button values are save in my database . this is my problem. I need only unique value in my database
protected void rd_CS_CheckedChanged(object sender, EventArgs e)
{
string myRadioText = String.Empty;
foreach (DataListItem item in DataList1.Items)
{
RadioButton rd_CS = (RadioButton)item.FindControl("rd_CS");
RadioButton rd_CS2 = (RadioButton)item.FindControl("rd_CS2");
RadioButton rd_CS3 = (RadioButton)item.FindControl("rd_CS3");
RadioButton rd_CS4 = (RadioButton)item.FindControl("rd_CS4");
if (rd_CS != null && rd_CS.Checked)
{
myRadioText = rd_CS.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS2 != null && rd_CS2.Checked)
{
myRadioText = rd_CS2.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS3 != null && rd_CS3.Checked)
{
myRadioText = rd_CS3.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS4 != null && rd_CS4.Checked)
{
myRadioText = rd_CS4.Text;
Label1.Text = myRadioText.ToString();
}
string str = Server.MapPath("~/App_Data/Quize.mdb");
OleDbConnection ole = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str + ";Persist Security Info=True");
ole.Open();
OleDbCommand cmd = new OleDbCommand("insert into Userdata values ('" + Label1.Text.Trim().Replace("'", "''") + "','" + Label1.Text.Trim().Replace("'", "''") + "',)", ole);
cmd.ExecuteNonQuery();
}
Related
I need to auto-Click on a hidden button after the Gridview is generated, I have:
$("#<%=btnExcel.ClientID%>").trigger("click");
works perfectly but I need to add it Codebehind after the Gridview is generated, I tried adding a function and then call it in the OnRowdatabound event:
//I tried creating a function
<script type="text/javascript">
function Excel() {
$("#<%=btnExcel.ClientID%>").trigger("click");
}
</script>
All CS code
public partial class ReportesCasos : System.Web.UI.Page
{
string BaseX = "SELECT DISTINCT Casos.Cliente AS idCliente, Casos.Asignado AS Usuario, Casos.idCaso AS 'N° Caso', Clientes.nombre AS Cliente,Asunto, Estado.Descripcion AS 'Estado Actual', Causa.Descripcion AS Causa_Raiz, Usuarios.Login AS 'Tecnico_Asignado', Zona.Descripcion AS 'Zona', Sector.Sector AS 'Sector', Usuarios.Login AS 'Asignado', CONVERT (nchar, Casos.Reportado, " + funciones.Fecha() + ") AS Reportado, CONVERT (nchar, Casos.Cerrado, " + funciones.Fecha() + ") AS Cerrado, CONVERT (nchar, Casos.Vencimiento, " + funciones.Fecha() + ") AS Vencimiento,fecha, CONVERT(nchar,fecha," + funciones.Fecha() + ") As Fecha2, TipoCaso.Descripcion AS TipoCaso, Prioridad.Descripcion AS Prioridad, Casos.Horas AS HorasTrabajadas, Casos.Atendidos AS EquiposAtendidos, Casos.Contrato AS BajoContrato, Casos.Valoracion AS Evaluacion, Casos.Facturado AS facturado, Casos.Factura AS 'N° Factura', Casos.Contacto AS ContactoCliente, Casos.Diagnostico AS Diagnostico, Casos.Solucion AS Solucion FROM Casos INNER JOIN TipoCaso ON Casos.TipoCaso = TipoCaso.idTipo INNER JOIN Prioridad ON Casos.Prioridad = Prioridad.idPrioridad INNER JOIN Estado ON Casos.Estado = Estado.idEstado INNER JOIN Usuarios ON Casos.Asignado = Usuarios.idUsuario INNER JOIN clientes ON idCliente = Casos.Cliente INNER JOIN (SELECT Caso,MAX(Fecha)AS Fecha FROM HistorialEstado";
string BaseX1 = " GROUP BY Caso) AS HistorialEstado ON Caso = idCaso INNER JOIN Zona ON Casos.Zona = Zona.idZona INNER JOIN Sector ON Casos.Sector = Sector.idSector INNER JOIN Causa ON Casos.Causa = Causa.idCausa WHERE tipocaso <> 5 AND ";
string ColaX2 = " ORDER BY idCaso";
string ClienteX = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["Usuario"] == null || Session["Sesion"] == null || !funciones.ChequearUsuario(Request.Cookies["Usuario"]["sesion"], Session["Sesion"].ToString()) || Session["Nivel"].ToString() == "3")
{
Response.Redirect("index.aspx");
}
Session["Titulo"] = "REPORTE EN GENERAL";
Session["Error"] = "";
if (Session["Cliente"].ToString() != "")
{
Cliente = " AND Casos.Cliente = '" + Session["Cliente"].ToString() + "'";
}
else
{
Cliente = "";
}
}
protected void dlPeriodo_SelectedIndexChanged(object sender, EventArgs e)
{
if (dlPeriodo.SelectedIndex != 6)
{
lblDesde.Visible = false;
lblHasta.Visible = false;
tbDesde.Visible = false;
tbHasta.Visible = false;
}
else
{
lblDesde.Visible = true;
lblHasta.Visible = true;
tbDesde.Visible = true;
tbHasta.Visible = true;
}
}
protected void btnVer2_Click(object sender, ImageClickEventArgs e)
{
if (dlPeriodo.SelectedIndex != 6)
{
SqlDataSourceBusqueda2.SelectCommand = BaseX + BaseX1 + " Fecha >= CONVERT(DateTime,'" + DateTime.Now.AddDays(-Int32.Parse(dlPeriodo.SelectedValue)).ToShortDateString() + "'," + funciones.Fecha() + ") AND Fecha <= CONVERT(DateTime,'" + DateTime.Now.AddDays(1).ToShortDateString() + "'," + funciones.Fecha() + ")" + ClienteX;
Session["Sql"] = SqlDataSourceBusqueda2.SelectCommand;
}
else
{
DateTime Fecha;
if (DateTime.TryParse(tbDesde.Text, out Fecha))
{
if (DateTime.TryParse(tbHasta.Text, out Fecha))
{
SqlDataSourceBusqueda2.SelectCommand = BaseX + BaseX1 + " Fecha >= CONVERT(DateTime,'" + DateTime.Now.AddDays(-Int32.Parse(dlPeriodo.SelectedValue)).ToShortDateString() + "'," + funciones.Fecha() + ") AND Fecha <= CONVERT(DateTime,'" + DateTime.Now.AddDays(1).ToShortDateString() + "'," + funciones.Fecha() + ")" + ClienteX;
Session["Sql"] = SqlDataSourceBusqueda2.SelectCommand;
}
else
{
string Formato = "";
if (funciones.Fecha() == "101")
{
Formato = " mm/dd/aaaa";
}
else
{
Formato = " dd/mm/aaaa";
}
Session["Error"] = "La fecha debe ser de la forma" + Formato;
}
}
else
{
string Formato = "";
if (funciones.Fecha() == "101")
{
Formato = " mm/dd/aaaa";
}
else
{
Formato = " dd/mm/aaaa";
}
Session["Error"] = "La fecha debe ser de la forma" + Formato;
}
}
}
protected void grdCartelera2_PageIndexChanged(object sender, EventArgs e)
{
SqlDataSourceBusqueda2.SelectCommand = Session["Sql"].ToString();
}
protected void grdCartelera2_Sorted(object sender, EventArgs e)
{
SqlDataSourceBusqueda2.SelectCommand = Session["sql"].ToString();
}
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "Redex_ReporteCasos"));
Response.Charset = "";
StringWriter stringwriter = new StringWriter();
HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
GridView2.RenderControl(htmlwriter);
Response.Write(stringwriter.ToString());
Response.End();
ExportGridToExcel();
}
protected void btnexportExcel_Click(object sender, ImageClickEventArgs e)
{
ExportGridToExcel();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (funciones.Anexos(((System.Web.UI.WebControls.HyperLink)(e.Row.Cells[1].Controls[0])).Text))
{
Image Imagen = new Image();
Imagen.ImageUrl = "~/Imagenes/Iconos/anexo.png";
e.Row.Cells[0].Text = "Si";
}
else
{
e.Row.Cells[0].Text = "No";
}
string BajoContrato = e.Row.Cells[15].Text.ToString();
if (BajoContrato == "False")
{
e.Row.Cells[15].Text = "No";
}
else
{
e.Row.Cells[15].Text = "Si";
}
btnexportExcel_Click(null, null);
}
}
public override void VerifyRenderingInServerForm(Control control) {}
}
ASPX
<table style="width: 770px; height: 492px">
<tr>
<td align="center" style="height: 7%;" valign="middle">
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Century Gothic"
ForeColor="#00C000" Text="En el periodo" Font-Size="Small"></asp:Label></td>
<td align="center" style="height: 7%;" valign="middle">
<asp:DropDownList ID="dlPeriodo" runat="server" BackColor="AliceBlue"
EnableTheming="True" Font-Bold="True" Font-Names="Century Gothic" ForeColor="#00C000"
OnSelectedIndexChanged="dlPeriodo_SelectedIndexChanged" Width="192px" Font-Size="Small" AutoPostBack="True">
<asp:ListItem Value="0">Hoy</asp:ListItem>
<asp:ListItem Value="1">1 Dia</asp:ListItem>
<asp:ListItem Value="5">5 Dias</asp:ListItem>
<asp:ListItem Value="7">7 Dias</asp:ListItem>
<asp:ListItem Value="15">15 Dias</asp:ListItem>
<asp:ListItem Value="30">30 Dias</asp:ListItem>
<asp:ListItem Value="6">Especifico</asp:ListItem>
</asp:DropDownList></td>
<td align="center" style="height: 7%; text-align: right;" valign="middle">
<asp:ImageButton ID="btnVer" runat="server" Height="24px" ImageUrl="~/Imagenes/Iconos/buscar.png"
OnClick="btnVer_Click" Width="22px" /></td>
<td align="left" colspan="1" valign="middle" class="style1">
<asp:ImageButton ID="btnVer0" runat="server"
Height="20px" ImageUrl="~/Imagenes/Iconos/excel.png"
OnClick="btnVer2_Click" Width="26px" />
<asp:ImageButton ID="btnExcel" style="visibility: hidden; display: none;" runat="server" ImageUrl="~/Imagenes/Iconos/excel.png"
OnClick="btnexportExcel_Click" Width="20px" Height="21px"/>
</td>
<td align="center" colspan="2" style="height: 7%" valign="middle">
</td>
</tr>
<tr>
<td align="center" style="height: 8%;" valign="middle">
<asp:Label ID="lblDesde" runat="server" Font-Bold="True" Font-Names="Century Gothic"
ForeColor="#00C000" Text="Desde" Visible="False" Font-Size="Small"></asp:Label></td>
<td align="center" style="height: 8%;" valign="middle">
<asp:TextBox ID="tbDesde" runat="server" BackColor="AliceBlue" Font-Bold="True" Font-Names="Century Gothic"
ForeColor="#00C000" MaxLength="50" Visible="False" Width="192px"
Font-Size="Small"></asp:TextBox></td>
<td align="center" style="height: 8%;" valign="middle">
<asp:Label ID="lblHasta" runat="server" Font-Bold="True" Font-Names="Century Gothic"
ForeColor="#00C000" Text="Hasta" Visible="False" Font-Size="Small"></asp:Label></td>
<td align="left" valign="middle" class="style2">
<asp:TextBox ID="tbHasta" runat="server" BackColor="AliceBlue" Font-Bold="True" Font-Names="Century Gothic"
ForeColor="#00C000" MaxLength="50" Visible="False" Width="192px"
Font-Size="Small"></asp:TextBox></td>
<td align="center" style="height: 8%" valign="middle" colspan="2">
</td>
</tr>
<tr>
<td align="left" colspan="6" style="height: 105%" valign="top">
<%if(Session["Nivel"].ToString() != "4"){ %>
<asp:GridView ID="GridView2" runat="server" AllowPaging="False"
CellPadding="2" DataSourceID="SqlDataSourceBusqueda2" Font-Names="Century Gothic"
ForeColor="#333333" GridLines="None" PageSize="50" Width="769px"
AutoGenerateColumns="False" Font-Size="Small"
OnPageIndexChanged="grdCartelera2_PageIndexChanged"
OnSorted="grdCartelera2_Sorted" OnRowDataBound="GridView2_RowDataBound">
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:ImageField HeaderText="Anexos">
</asp:ImageField>
<asp:HyperLinkField DataNavigateUrlFields="N° Caso" DataNavigateUrlFormatString="Casos.aspx?idCaso={0}"
DataTextField="N° Caso" HeaderText="Caso"
SortExpression="N° Caso" />
<asp:BoundField DataField="Cliente" HeaderText="Cliente" SortExpression="Cliente" />
<asp:BoundField DataField="ContactoCliente" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Contacto Cliente" SortExpression="ContactoCliente" />
<asp:BoundField DataField="TipoCaso" HeaderText="Tipo Caso" SortExpression="TipoCaso" />
<asp:BoundField DataField="Asunto" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Asunto" SortExpression="Asunto" />
<asp:BoundField DataField="Asignado" HeaderText="Tecnico" SortExpression="Asignado" />
<asp:BoundField DataField="Causa_Raiz" HeaderText="Causa Raiz" SortExpression="Causa_Raiz" />
<asp:BoundField DataField="Zona" HeaderText="Zona" SortExpression="Zona" />
<asp:BoundField DataField="Sector" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Sector" SortExpression="Sector" />
<asp:BoundField DataField="Estado Actual" HeaderText="Estado" SortExpression="Estado Actual" />
<asp:BoundField DataField="Prioridad" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Prioridad" SortExpression="Prioridad" />
<asp:BoundField DataField="HorasTrabajadas" HeaderText="Horas Trabajadas" SortExpression="HorasTrabajadas" />
<asp:BoundField DataField="Evaluacion" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Evaluacion" SortExpression="Evaluacion" />
<asp:BoundField DataField="EquiposAtendidos" HeaderText="Equipos Atendidos" SortExpression="EquiposAtendidos" />
<asp:BoundField DataField="BajoContrato" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Bajo Contrato" SortExpression="BajoContrato" />
<asp:BoundField DataField="N° Factura" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="N°Factura" SortExpression="N° Factura" />
<asp:BoundField DataField="Diagnostico" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Diagnostico" SortExpression="Diagnostico" />
<asp:BoundField DataField="Solucion" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Solucion" SortExpression="Solucion" />
<asp:BoundField DataField="Reportado" HeaderText="Reportado" SortExpression="Reportado" />
<asp:BoundField DataField="Cerrado" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Cerrado" SortExpression="Cerrado" />
<asp:BoundField DataField="Vencimiento" HeaderText="Vencimiento" SortExpression="Vencimiento" />
</Columns>
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<%}%>
<asp:SqlDataSource ID="SqlDataSourceBusqueda2" runat="server" ConnectionString="<%$ ConnectionStrings:conexion %>"
ProviderName="<%$ ConnectionStrings:conexion.ProviderName %>"></asp:SqlDataSource>
There are several solutions to this but it would take you to try out multiple of them so you can analyze which one suits your needs.
Solution 1 If you intend to execute a server side event, you can simply call that method from your code behind instead of faking the click. Call your event method like this in the code behind.
btnExcel_Clicked(null, null);
You can consume it like this:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
// ... Your code
btnExcel_Clicked(null, null); // I assume your btnExcel button is linked to this event.
}
Solution 2 If it is required that you must only use JavaScript/Jquery this can be helpful.
var myButtonID = btnExcel.ClientID;
Page.ClientScript.RegisterStartupScript(this.GetType(), "Trigger",
"$("#"+ myButtonID +"").trigger("click");", true);
Solution 3 Solution 2, with javascript event.
var myButtonID = btnExcel.ClientID;
Page.ClientScript.RegisterStartupScript(this.GetType(), "Trigger",
"document.getElementById(" + myButtonID + ").onclick();", true);
I do not think it is a good Idea to call it on a RowDataBound event, as it will trigger it many times not only when the grid view is loaded. So, you must call it after you have called GridView2.DataBind() method, not inside of a RowDataBound event.
Solution 4 This is a pure, page flow based solution. The trick is to execute the javascript from the javascript by using a CodeBehind flag. Here it is how you would do that:
First Declare a property in the CodeBehind.
public bool ShouldTriggerClickEvent { get; set; }
Then, in your Page_Load event, assign flase as value to this property, and make it true when your RowDataBound event is completely triggered. See:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
ShouldTriggerClickEvent = false;
}
}
Now, in your RowDataBound event make it true.
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
// ... Your code
ShouldTriggerClickEvent = true;
}
And now, when the page load completes, you need to check this flag on the client side, and execute the code if the flag is true. Like below:
<script>
$(document).ready(function(){
function shouldTriggerClickEvent(){
return '<%= ShouldTriggerClickEvent %>' == 'True';
}
if (shouldTriggerClickEvent()){
$("#<%=btnExcel.ClientID%>").trigger("click");
}
});
</script>
I have mentioned multiple solution that I could so far memorize, you can see which one works for you fine.
UPDATE
As you are asking where to call the method, I would suggest calling the method right after you bind your DataSource.
// After this line
GridView2.DataBind(); // so each time the data is populated in it, this will method will be called
btnExcel_Clicked(null, null);
You can also check if your DataSource has items in it, only then you might want to call it, as you asked when the GridView is loaded, which I assume means, will only load after it has rows in it.
// Lets assume you have a DataTable object that is the DataSource of the GridView
var dataTable = GetDataTable(); // Some method that will fetch the rows
GridView2.DataSource = dataTable;
GridView2.DataBind(); // so each time the data is populated in it, this will method will be called
if (dataTable != null && dataTable.Rows.Count > 0)
{
btnExcel_Clicked(null, null);
}
UPDATE 2
Okay, so you want to call execute the Event after the Data has been bound to your GridView and you are using SqlDataSource to bind the GridView. Here is my suggestion on modification.
Replace your SqlDataSource to include OnSelected event.
<asp:SqlDataSource ID="SqlDataSourceBusqueda2" runat="server"
ConnectionString="<%$ ConnectionStrings:conexion %>"
ProviderName="<%$ ConnectionStrings:conexion.ProviderName %>"
OnSelected="SqlDataSourceBusqueda2_Selected">
</asp:SqlDataSource>
And Add this method/event inside of your CodeBehind
protected void SqlDataSourceBusqueda2_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
// Your Code goes here.
btnExcel_Clicked(null, null);
}
I'm using a Textbox and a DropDownList to filter database searches. I'm using an SQLDataSource with a blank SelectCommand and then setting the command in the codebehind depending on what the user has typed in and what is selected in the DropDownList. My IF statements in the codebehind only work if txtFindBook != "".
Before I explain anymore here is my code:
Default.aspx
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="jumbotron">
<h1>Find a book...</h1>
<p>
<asp:TextBox ID="txtFindBook" runat="server" Width="700px"></asp:TextBox>
<asp:DropDownList ID="ddlGenres" runat="server"></asp:DropDownList>
<asp:Button ID="btnFindBook" runat="server" Text="Search" OnClick="btnFindBook_Click" Height="36px" />
<p>Enter your search terms in the box above, then click "Search" to begin your search.</p>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
<div class="searchresults">
<asp:GridView ID="gvSearchResults" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSourceSearchResults">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" InsertVisible="False" SortExpression="ID"></asp:BoundField>
<asp:BoundField DataField="BookID" HeaderText="BookID" SortExpression="BookID"></asp:BoundField>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title"></asp:BoundField>
<asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author"></asp:BoundField>
<asp:BoundField DataField="ISBN_10" HeaderText="ISBN_10" SortExpression="ISBN_10"></asp:BoundField>
<asp:BoundField DataField="ISBN_13" HeaderText="ISBN_13" SortExpression="ISBN_13"></asp:BoundField>
<asp:BoundField DataField="Dewey" HeaderText="Dewey" SortExpression="Dewey"></asp:BoundField>
<asp:BoundField DataField="Genre" HeaderText="Genre" SortExpression="Genre"></asp:BoundField>
<asp:CheckBoxField DataField="isCheckedOut" HeaderText="isCheckedOut" SortExpression="isCheckedOut"></asp:CheckBoxField>
<asp:BoundField DataField="Checked_Out_To_Whome" HeaderText="Checked_Out_To_Whome" SortExpression="Checked_Out_To_Whome"></asp:BoundField>
<asp:BoundField DataField="Due_Date" HeaderText="Due_Date" SortExpression="Due_Date"></asp:BoundField>
</Columns>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSourceSearchResults" ConnectionString='<%$ ConnectionStrings:DefaultConnection %>' SelectCommand="">
<SelectParameters>
<asp:ControlParameter ControlID="txtFindBook" PropertyName="Text" Name="Title" Type="String"></asp:ControlParameter>
<asp:ControlParameter ControlID="ddlGenres" PropertyName="SelectedValue" DefaultValue="Select Genre" Name="Genre" Type="String"></asp:ControlParameter>
</SelectParameters>
</asp:SqlDataSource>
</div>
Default.aspx.cs
public partial class _Default : Page
{
static string connString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
/*There is no point in populating
the dropdownlist everytime there
is a post back. */
populateddlGenres();
}
}
protected void btnFindBook_Click(object sender, EventArgs e)
{
if (txtFindBook.Text != "" && ddlGenres.SelectedItem.Text != "Select Genre")
{
SqlDataSourceSearchResults.SelectCommand = "SELECT * FROM [Books] WHERE (([Title] LIKE '%' + #Title + '%') AND ([Genre] = #Genre)) ORDER BY [Title]";
Label1.Text = "If Statement 1.";
}
else if (txtFindBook.Text == "" && ddlGenres.SelectedItem.Text != "Select Genre")
{
Label1.Text = "If Statement 2.";
SqlDataSourceSearchResults.SelectCommand = "SELECT * FROM [Books] WHERE ([Genre] = #Genre)";
}
else if (txtFindBook.Text == "" && ddlGenres.SelectedItem.Text == "Select Genre")
{
SqlDataSourceSearchResults.SelectCommand = "SELECT * FROM [Books]";
Label1.Text = "If Statement 3.";
}
else if(txtFindBook.Text != "" && ddlGenres.SelectedItem.Text == "Select Genre")
{
SqlDataSourceSearchResults.SelectCommand = "SELECT * FROM [Books] WHERE ([Title] LIKE '%' + #Title + '%') ORDER BY [Title]";
Label1.Text = "Original.";
}
}
private void populateddlGenres()
{
try
{
using (SqlConnection con = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Genres", con);
con.Open();
ddlGenres.DataSource = cmd.ExecuteReader();
ddlGenres.DataTextField = "GenreText";
//ddlGenres.DataValueField = ""; //We aren't using this because the text is it's own value.
ddlGenres.DataBind(); //MUST GO LAST!
}
}
catch (Exception ex)
{
// Handle the error
}
ddlGenres.Items.Insert(0, new ListItem("Select Genre", "0"));
}
}
Now If I add txtFindBook.text = "a"; at the beginning of If Statements 2 & 3 then it will actually populate gvSearchResults on PostBack.
Is there someway I can still have If statements 2 & 3 work while keeping txtFindBook.Text blank?
Modify your SqlDataSource by adding a default value of NULL to your Title property defined on it and that should do the trick. You will not need the labels, I didn't understand the label thing anyway.
<asp:SqlDataSource runat="server" ID="SqlDataSourceSearchResults" ConnectionString='<%$ ConnectionStrings:DefaultConnection %>' SelectCommand="">
<SelectParameters>
<asp:ControlParameter ControlID="txtFindBook" PropertyName="Text" DefaultValue="NULL" Name="Title" Type="String"></asp:ControlParameter>
<asp:ControlParameter ControlID="ddlGenres" PropertyName="SelectedValue" DefaultValue="Select Genre" Name="Genre" Type="String"></asp:ControlParameter>
</SelectParameters>
</asp:SqlDataSource>
Greetings to all
Actually i'm developing a web application Which will generate DataGrid,Button and a Label at run time depends upon the value return from database.
Eg:
if return value is 2 then the 3 controls(datagrid,button and label) will generate twice.like shown below
Application working Procedure is.On click on search button the above 3 controls are generated and bind the datagrid.I have achieved this using repeater.
Now what i need is....inside that datagrid i have a button called refresh.When the Refresh button is clicked the gross weight and volume in the datagrid should display the string value,remaining columns should not get change.
Here is my aspx code:
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:Label ID="textBoxSearch" ForeColor="White" width="25%" runat="server"
Text="<%#Container.DataItem%>"></asp:Label>
<asp:Button ID="BTNAdd" runat="server" Text="Add" OnClick="button_click"/>
<br />
<asp:DataGrid ID="dgLCL" runat="server" AutoGenerateColumns="False"
ShowFooter="FALSE" CellPadding="3" OnItemCommand="dgLCL_Select"
OnDeleteCommand="dgLCL_Delete">
<asp:BoundColumn DataField="GrossUOMType" HeaderText="Type">
</asp:BoundColumn>
<asp:BoundColumn DataField="Volume" HeaderText="Volume">
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="DELETE">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNDelete"
ImageUrl="~/AppImages/grid-icon-delete.jpg"
ToolTip="Delete" CommandName="DeleteItem"
OnClientClick="javascript:return confirmDelete();"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Add">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNAdd"
ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="InsertItem"
AlternateText="Insert" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White"
Mode="NumericPages">
</PagerStyle>
</asp:DataGrid><br />
and my code behind is:
protected void repeaterSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string Flag = Session["Flag"].ToString();
if (Flag=="B")
{
e.Item.FindControl("textBoxSearch").Visible = false;
e.Item.FindControl("BTNAdd").Visible = false;
}
DataGrid gv = e.Item.FindControl("dgLCL") as DataGrid;
//
Label label = e.Item.FindControl("textBoxSearch") as Label;
Session["Label"] = label.Text;
Session["FlagB"] = Flag;
Session["GV"] = gv;
gridbind(label.Text, Flag, gv);
}
void gridbind(string label,string Flag,DataGrid gv)
{
try
{
if (Session["Loading"] != null)
{
PortLName.Text = Session["Loading"].ToString();
}
if (Session["Destination"] != null)
{
PortDName.Text = Session["Destination"].ToString();
}
string SFRID = label;
if (Flag == "L")
{
sql = "Select MasterNo , MasterDate,GrossWt,GrossUOMType,Volume,tBLg_NUPKId from VW_TransLCLMaster where tBLG_mDOC_NUPKID ='107' and tBLG_NUIsActive=1 and PortOfDischargeName='" + SFRID + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (gv != null)
{
gv.DataSource = ds;
gv.DataBind();
}
}
}
catch (Exception ex)
{
}
as shown in above image i need the string values should assign to grosswt and volume on refresh button click.
Please help me thanks in advance.
In your datagrid columns add another column
<asp:TemplateColumn HeaderText="Refresh">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNRefresh"
ImageUrl="~/AppImages/grid-icon-refresh.jpg"
ToolTip="Insert" CommandName="Refresh"
AlternateText="Refresh" />
</ItemTemplate>
</asp:TemplateColumn>
In your DagaGrid's OnItemCommand event, set the text for both the cells as below
protected void dgLCL_Select(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Refresh")
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Change the indexes to correct column index
e.Item.Cells[3].Text = "your dynamic gross weight text";
e.Item.Cells[5].Text = "your dynamic volumne text";
}
}
}
I am about to develop a web application which is used to search and fetch the data from the database as per the criteria which we enter in textboxes.
I have from place and to place once we enter the data in either textbox and hit search button it will fetch data from database and display in textbox (dynamic).
Eg:
if I enter a place kolkata and hit enter then it will count the total no of records that has the from place kolkatta. If count is 3 then 3 textboxes, 3 buttons (add) and 3 gridviews should be created dynamically. Then if we click the add button it will redirect to next page.
I have created a textbox and a button but I'm unable to create 3 gridviews and also click event for the button is not firing.
Here is my code for creating controls dynamically on search button click:
protected void BTNSearch_Click(object sender, EventArgs e)
{
if(Convert.ToInt32( Session["Count"])>0)
{
if (Flag != "")
{
LoadControls(Flag);
}
}
}
private void LoadControls(string Flag)
{
LocationName.Clear();
Session["Flag"] = Flag;
Updatesearch.Update();
dynamicTextBoxes = new TextBox[Convert.ToInt32(Session["Count"])];
dynamicButtons = new Button[Convert.ToInt32(Session["Count"])];
dynamicGV = new GridView[Convert.ToInt32(Session["Count"])];
int i;
if (Flag == "L")
{
sql = "Select PortOfDischargeName from VW_TransAIHBLMasterUpdateDetails where tBLG_NUIsActive=1 and PortOfLoadName='" + Session["Loading"].ToString() + "' group by PortOfDischargeName";
}
else if (Flag == "D")
{
sql = "Select PortOfLoadName from VW_TransAIHBLMasterUpdateDetails where tBLG_NUIsActive=1 and PortOfDischargeName='" + Session["Destination"].ToString() + "' group by PortOfLoadName";
}
else
{
sql = "";
}
SqlDataReader rdr = mobjGenlib.objDBLib.ExecuteQueryReader(sql.ToString());
while (rdr.Read())
{
LocationName.Add(rdr.GetValue(0).ToString());
}
rdr.Close();
for (i = 0; i < Convert.ToInt32(Session["Count"]); i += 1)
{
TextBox textBox = new TextBox();
textBox.ID = "myTextBox" + i.ToString();
textBox.Width = 200;
textBox.Height = 15;
//textBox.Text = String.Empty;
textBox.Text = LocationName[i].ToString();
textBox.BackColor = System.Drawing.Color.AliceBlue;
myPlaceHolder.Controls.Add(textBox);
dynamicTextBoxes[i] = textBox;
var button = new Button();
button.ID = "BtnAdd" + i.ToString();
button.Text = "Add";
//button.Click += button_Click;
button.Click += new System.EventHandler(button_click);
//btn.Click += new EventHandler(btn_Click);
myPlaceHolder.Controls.Add(button);
dynamicButtons[i] = button;
ViewState["Btn"] = dynamicButtons[i];
LiteralControl literalBreak = new LiteralControl("<br />");
myPlaceHolder.Controls.Add(literalBreak);
gv.ID = "gridview" + i;
myPlaceHolder.Controls.Add(gv);
dynamicGV[i] = gv;
BindGrid(textBox.Text, Flag, i);
LiteralControl literalBreak1 = new LiteralControl("<br />");
myPlaceHolder.Controls.Add(literalBreak1);
}
}
This is for button click:
protected void button_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
foreach (Button bt in dynamicButtons)
{
for (int i = 0; i < Convert.ToInt32(Session["Count"]); i++)
{
if (btn.ID == ("BtnAdd" + i))
{
Response.Redirect("FrmTransLCLConsolidation.aspx");
break;
}
}
}
}
**
> i dont know how to write code to the Datagrid onitemcommand and > ondeletecommand.
**
Can anyone help me to achieve this? Thanks in advance.
another issue:
aspx page:
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:Label ID="textBoxSearch" ForeColor="White" width="25%" runat="server" Text="<%#Container.DataItem%>"></asp:Label>
<%--<asp:TextBox ID="textBoxSearch" runat="server" Text="<%#Container.DataItem%>"></asp:TextBox>--%>
<asp:Button ID="BTNAdd" runat="server" Text="Add" OnClick="button_click"/><br />
<asp:DataGrid ID="dgLCL" runat="server" BorderWidth="1px" BorderColor="#FE9B00"
BorderStyle="Solid" BackColor="White" Font-Names="Verdana" Font-Size="XX-Small"
AutoGenerateColumns="False" ShowFooter="FALSE" CellPadding="3" align="center"
Width="700px" OnItemCommand="dgLCL_Select" OnDeleteCommand="dgLCL_Delete">
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
<SelectedItemStyle Font-Bold="True" ForeColor="Black" BackColor="Snow"></SelectedItemStyle>
<EditItemStyle BackColor="AntiqueWhite"></EditItemStyle>
<PagerStyle BackColor="#FDE9CB" ForeColor="#003399" HorizontalAlign="Right" Mode="NumericPages"
Position="Bottom" Font-Size="Small" Font-Bold="true" />
<AlternatingItemStyle BackColor="Snow"></AlternatingItemStyle>
<ItemStyle ForeColor="#000066" BackColor="Snow"></ItemStyle>
<HeaderStyle Font-Size="XX-Small" Font-Bold="True" Height="10px" ForeColor="#000000"
BackColor="#FFDBA6"></HeaderStyle>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNAdd" ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="SelectItem" AlternateText="Insert" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="MasterNo" HeaderText="MasterNo"></asp:BoundColumn>
<asp:BoundColumn DataField="MasterDate" HeaderText="MasterDate"></asp:BoundColumn>
<asp:BoundColumn DataField="GrossWt" HeaderText="GrossWt"></asp:BoundColumn>
<asp:BoundColumn DataField="GrossUOMType" HeaderText="Type"></asp:BoundColumn>
<asp:BoundColumn DataField="Volume" HeaderText="Volume"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="DELETE">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNDelete" ImageUrl="~/AppImages/grid-icon-delete.jpg"
ToolTip="Delete" CommandName="DeleteItem" OnClientClick="javascript:return confirmDelete();"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White" Mode="NumericPages">
</PagerStyle>
</asp:DataGrid><br />
</ItemTemplate>
</asp:Repeater>
Repeater is a good candidate for this problem. Instead of adding the textboxes dynamically use a repeater control here, which is then easier to maintain.
Below is the outline of what you can do.
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:TextBox ID="textBoxSearch" runat="server" Text="<%#Container.DataItem%>"></asp:TextBox>
<asp:Button ID="buttonAdd" runat="server" Text="Button" OnClick="button_click"/>
<asp:GridView ID="gridView" runat="server">
<%--Add the Columns you want to display--%>
</asp:GridView>
</ItemTemplate>
</asp:Repeater>
In your code, after getting the search result from the data reader, instead of creating the textbox and buttons, bind the result to the repeater
SqlDataReader rdr = mobjGenlib.objDBLib.ExecuteQueryReader(sql.ToString());
while (rdr.Read())
{
LocationName.Add(rdr.GetValue(0).ToString());
}
rdr.Close();
repeaterSearchResult.DataSource = LocationName;
repeaterSearchResult.DataBind();
In the repeaters OnItemDataBound, bind the grid view
protected void repeaterSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
GridView gv = e.Item.FindControl("gridView") as GridView;
TextBox textBox = e.Item.FindControl("textBoxSearch") as TextBox;
if (gv != null)
{
//Bind gridview here
}
}
In the button click event you can redirect to the page. You can also use the command argument for the button to identify the current index if you want.
Further to your question to open a new form you can use the following method.
In your image button add onclientclick event as below.
<asp:ImageButton runat="server" OnClientClick="return openNewForm();" ID="IMGBTNAdd" ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="SelectItem" AlternateText="Insert" />
Then add a javascript function to open the popup
<script type="text/javascript">
function openNewForm() {
window.open("url for the new form", "newForm", "menubar=0,resizable=1,location=0,status=0,scrollbars=1,height=500,width=600");
return false;
}
</script>
I am creating the update button for the cart system in asp.net. What am I trying to do is to allow user key in the quantity items and then click the update button. Here is the design of the shopping cart system...
Unfortunately the update button doesn't work properly after the first row. I have debugged the problem and the for loop inside the btn_update_Click method returns the value of zero.
Is there any other way to overcome the problem? Thanks
Here is the source code:
<b><asp:Label ID="lbl_showResult" runat="server" Text=""></asp:Label></b>
<asp:GridView ID="grv_cart" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True" GridLines="None" CssClass="table">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a class="hyp_productimage imgLiquidFill imgLiquid productImage img-responsive" href='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'>
<img src='<%#Eval("image") %>' />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Hyperlink ID="hyp_productname" Text='<%# Eval("product_name") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txt_productQuantity" Text='<%# Eval("product_quantity") %>' CssClass="form-control" runat="server" Width="60" MaxLength="5"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_update" Text="Update" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" OnClick="btn_update_Click" />
<asp:Button ID="btn_remove" Text="Delete" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-danger" onclick="btn_remove_Click"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cost">
<ItemTemplate>
<asp:Hyperlink ID="hyp_productcost" Text='<%#"$"+Eval("product_cost") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sds_store" runat="server"
ConnectionString="<%$ ConnectionStrings:websiteConnection %>"
SelectCommand="SELECT [id], [product_id], [product_name], [product_cost], [product_description], [product_quantity], [image], [date] FROM [tbl_cart] WHERE [name] = #username AND [visible] = #visible">
<SelectParameters>
<asp:sessionparameter sessionfield="login" Name="username" />
<asp:Parameter Name="visible" Type="string" DefaultValue="true" />
</SelectParameters>
</asp:SqlDataSource>
<h4><asp:Label ID="lbl_totalCost" Text="" runat="server" CssClass="pull-right"></asp:Label></h4>
<br /><br /><br />
<asp:Button ID="btn_buy" Text="Buy Now" runat="server" CssClass="btn btn-success btn-lg pull-right" OnClick="btn_buy_Click" />
Here's another source code for the .cs:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace websiteEcom
{
public partial class cart : System.Web.UI.Page
{
// Open the connection for the sql
private static SqlConnection conn;
private static SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
// Create an instance for the connection of database
string connectionString = ConfigurationManager.ConnectionStrings["websiteConnection"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
// Checks how many items are there inside the cart database and display it to the label
CheckHowManyItem();
// Multiply all the sums of the cost
lbl_totalCost.Text = "Total Cost: $"+TotalProductCost().ToString();
}
// Checks how many items are there inside the cart database and display it to the label
public void CheckHowManyItem()
{
try
{
conn.Open();
// Retrieve the number of rows from the database
string query = string.Format("SELECT COUNT(*) FROM tbl_cart WHERE name = '{0}' AND visible = '{1}'", Session["login"], "true");
command.CommandText = query;
int numberOfItems = (int)command.ExecuteScalar();
// If the number of rows is zero
if (numberOfItems == 0)
{
lbl_showResult.Text = "You have no items inside the cart.";
btn_buy.Visible = false;
}
else
{
// If there is number of rows inside
lbl_showResult.Text = "There are currently " + numberOfItems + " inside the cart.";
btn_buy.Visible = true;
}
}
finally
{
conn.Close();
}
}
protected void btn_remove_Click(object sender, EventArgs e)
{
// Get the value from the button ASP.NET gridview
Button btn = (Button)sender;
try
{
conn.Open();
// Make the cart invisible if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET visible = '{0}' WHERE id = '{1}'", "false", btn.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
// Multiply all the values of purchases together
public int TotalProductCost()
{
int totalCost = 0;
int currentCost = 0;
int currentQuantity = 0;
for (int i = 0; i < grv_cart.Rows.Count; i++)
{
// Get the data values from the forms
HyperLink hypCost = (HyperLink)grv_cart.Rows[i].Cells[0].FindControl("hyp_productcost");
TextBox txtQuantity = (TextBox)grv_cart.Rows[i].Cells[0].FindControl("txt_productQuantity");
// Sum the product quantity and the product cost
// Attempt to parse your value (removing any non-numeric values)
currentQuantity = Int32.Parse(Regex.Replace(txtQuantity.Text, #"[^\d]", ""));
// Attempt to parse your value (removing any non-numeric values)
currentCost = Int32.Parse(Regex.Replace(hypCost.Text, #"[^\d]", ""));
currentCost *= currentQuantity;
totalCost += currentCost;
}
return totalCost;
}
protected void btn_buy_Click(object sender, EventArgs e)
{
}
protected void btn_update_Click(object sender, EventArgs e)
{
// Get the value from the button ASP.NET gridview
Button btn = (Button)sender;
foreach (GridViewRow grvCart in grv_cart.Rows)
{
Debug.WriteLine(btn.CommandArgument);
TextBox textQuantity = (TextBox)grvCart.FindControl("txt_productQuantity");
int currentQuantity = Int32.Parse(Regex.Replace(textQuantity.Text, #"[^\d]", ""));
try
{
conn.Open();
// Update the cart quantity if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET product_quantity = '{0}' WHERE id = '{1}'", currentQuantity, btn.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
}
}
}
Try using the RowCommand event (especially since you already have the CommandArgument set up). That is the more appropriate way to handle this type of action (and that way you can just update one row at a time, without looping through all of them).
Handle the RowCommand event in your GridView declaration:
<asp:GridView ID="grv_cart" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True"
GridLines="None" CssClass="table" OnRowCommand="grv_cart_RowCommand">
And then your event handler would look like this:
protected void grv_cart_RowCommand(Object sender, GridViewCommandEventArgs e)
{
GridViewRow rowToUpdate = grv_cart.Rows[Int.Parse(e.CommandArgument)];
TextBox textQuantity = (TextBox)rowToUpdate.FindControl("txt_productQuantity");
int currentQuantity = Int32.Parse(Regex.Replace(textQuantity.Text, #"[^\d]", ""));
try
{
conn.Open();
// Update the cart quantity if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET product_quantity = '{0}' WHERE id = '{1}'", currentQuantity, e.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
Note: You'll want to remove the OnClick handler from the update button:
<asp:Button ID="btn_update" Text="Update" runat="server"
CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" />