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);
}
Related
Error on RowUpdating >> GridView 'GView' fired the RowUpdating event, which was not handled.
I put the RowEditing and I can enter to update the data, but when I put public void GView_UpdateItem(int id) {} it returns the error saying GridView 'GView' triggered the RowUpdating event, which was not handled.
<asp:GridView runat="server" ID="GView" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowEditing="GView_RowEditing" UpdateMethod="GView_UpdateItem">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ShowEditButton="True"></asp:CommandField>
<asp:CommandField ShowDeleteButton="True"></asp:CommandField>
</Columns>
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
}
public static List<Contato> contatos = new List<Contato>();
public void btnCad(object sender, EventArgs e)
{
Contato contato = new Contato();
contato.Id = contatos.Count;
contato.Nome = this.txtNome.Text;
contato.Idade = this.txtIdade.Text;
contato.Telefone = this.txtTelefone.Text;
contato.Genero = this.txtGenero.Text;
contato.DataCadastro = this.txtDataCad.Text;
contatos.Add(contato);
GView.DataSource = contatos;
GView.DataBind();
}
public void GView_UpdateItem(int id)
{
VoxTraining.Models.Contato item = contatos.Find(cont => cont.Id == id);
if (item == null)
{
ModelState.AddModelError("", String.Format("O item com id {0} não foi encontrado", id));
return;
}
TryUpdateModel(item);
if (ModelState.IsValid)
{
}
}
protected void GView_RowEditing(object sender, GridViewEditEventArgs e)
{
return ;
}
Ok, a few things.
Yes, we can do this without a database. We have have to persist our "list of names".
Dump the delete and edit buttons for the GV - they not worth the trouble - they don't help you.
So, we have the edit area, and the grid.
So, we have this markup:
<div id="myedit" runat="server" style="width:30%;padding:35px;display:none">
<div cssclass="form-group">
<label for="exampleInputEmail1">Nome</label>
<asp:TextBox CssClass="form-control" runat="server" ID="txtNome"></asp:TextBox>
</div>
<div cssclass="form-group">
<label for="exampleInputPassword1">Idade</label>
<asp:TextBox CssClass="form-control" runat="server" ID="txtIdade"></asp:TextBox>
</div>
<div cssclass="form-group">
<label for="exampleInputPassword1">Telefone</label>
<asp:TextBox CssClass="form-control" runat="server" ID="txtTelefone"></asp:TextBox>
</div>
<asp:Label runat="server" AssociatedControlID="txtGenero" ><b>Genero</b></asp:Label><br />
<asp:DropDownList CssClass="form-group" checked="" ID="txtGenero" runat="server" OnSelectedIndexChanged="btnCad">
<asp:ListItem Text="Masculino" />
<asp:ListItem Text="Feminino" />
</asp:DropDownList>
<div cssclass="form-group">
<label for="exampleInputPassword1">Data de Cadastro</label>
<asp:TextBox CssClass="form-control" runat="server" TextMode="Date" ID="txtDataCad"></asp:TextBox>
</div>
<br />
<asp:Button runat="server" ID="IDbtnCad" CssClass="btn" Text="Save" OnClick="btnCad" />
<asp:Button runat="server" ID="btnCancel" CssClass="btn" Text="Cancel" OnClick="btnCancel_Click"
style="margin-left:20px" />
<asp:Button runat="server" ID="btnDelete" CssClass="btn" Text="Delete" OnClick="btnCancel_Click"
style="margin-left:30px" />
</div>
<div id="MyGrid" runat="server">
<asp:Button ID="cmdNew" runat="server" Text="+Add new" CssClass="btn" OnClick="cmdNew_Click"/>
<asp:GridView runat="server" ID="GView" CellPadding="4" ForeColor="#333333" cssclass="table" Width="40%"
ShowHeaderWhenEmpty="true" >
<Columns>
<asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdEdit" runat="server" Text="Edit" CssClass="btn" OnClick="cmdEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"></HeaderStyle>
</asp:GridView>
</div>
And code to load is this:
List<Contato> MyNames = new List<Contato>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["MyNames"] = MyNames;
GView.DataSource = MyNames;
GView.DataBind();
}
else
MyNames = ViewState["MyNames"] as List<Contato>;
}
Note how we save the list of names.
So, we now have this:
so, add new button is thus this:
protected void cmdNew_Click(object sender, EventArgs e)
{
// add new
Contato OneName = new Contato();
MyNames.Add(OneName);
MyEdit(MyNames.Count - 1);
}
And my edit is this:
void MyEdit(int RowIndex)
{
Contato OneName = MyNames[RowIndex];
txtNome.Text = OneName.Nome;
txtIdade.Text = OneName.Idade;
txtTelefone.Text = OneName.Telefone;
txtGenero.Text = OneName.Genero;
txtDataCad.Text = OneName.DataCadastro;
ViewState["RowIndex"] = RowIndex;
// show editor, hide grid
myedit.Style.Add("Display", "nomral");
MyGrid.Style.Add("display", "none");
}
so, we hit add, and we now have this:
We hit save button, this code
protected void btnCad(object sender, EventArgs e)
{
int RowIndex = (int)ViewState["RowIndex"];
Contato OneName = MyNames[RowIndex];
OneName.Nome = this.txtNome.Text;
OneName.Idade = this.txtIdade.Text;
OneName.Telefone = this.txtTelefone.Text;
OneName.Genero = this.txtGenero.Text;
OneName.DataCadastro = txtDataCad.Text;
ViewState["MyNames"] = MyNames;
myedit.Style.Add("Display", "none");
MyGrid.Style.Add("display", "normal");
GView.DataSource = MyNames;
GView.DataBind();
}
And we now have this:
We can use add again, and now this:
the edit row button - plane jane asp.net button click.
Code is this:
protected void cmdEdit_Click(object sender, EventArgs e)
{
Button btnEdit = sender as Button;
GridViewRow gRow = btnEdit.NamingContainer as GridViewRow;
MyEdit(gRow.RowIndex);
}
So, hitting edit button, goes back to the editor.
Say like this:
Cancel button - does nothing (no save, return to grid).
Say this:
protected void btnCancel_Click(object sender, EventArgs e)
{
myedit.Style.Add("Display", "none");
MyGrid.Style.Add("display", "normal");
}
And the delete button - that would just remove the current row index item from the list.
eg:
protected void cmdDel_Click(object sender, EventArgs e)
{
myedit.Style.Add("Display", "none");
MyGrid.Style.Add("display", "normal");
int RowIndex = (int)ViewState["RowIndex"];
MyNames.RemoveAt(RowIndex);
GView.DataSource = MyNames;
GView.DataBind();
}
It's been a long time since I've had to work with WebForms but I'm having to update an old website. I'm trying to make a page that will allow the user to download a file to their machine. I can get the list of files in a directory as well as display it in a table, however, I'm trying to assign the file name to the command argument of a button so that I'll know the name of the file to go get in the button event. I can't seem to find the correct way to get the value out of the folder object to populate the command argument. No errors, it's just blank. Any suggestions?
var listFiles = dir.GetFiles();
<%
foreach(var file in listFiles) { %>
<tr>
<td> </td>
<td><%= file.Name %></td>
<td><%= file.Length %></td>
<td><%= file.CreationTime.ToString("MM/dd/yyyy HH:mm") %></td>
<td>
<asp:LinkButton ID="btnDownload" runat="server"
CommandArgument='<%#Eval("file.Name") %>'
CommandName="DownloadTechFile"
OnCommand="DownloadFile"
ToolTip="Downloaded file">
<span aria-hidden="true" class="fa fa-download"></span>
</asp:LinkButton>
</td>
</tr>
<% } %>
protected void DownloadFile(object sender, CommandEventArgs e)
{
Alert.Hide();
var fileName = e.CommandArgument.ToString();
var fileFullPath = Path.Combine(FileFolderPath, fileName);
if (string.IsNullOrWhiteSpace(fileName) == false)
{
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
try
{
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] data = req.DownloadData(fileFullPath);
//byte[] data = req.DownloadData(Server.MapPath(fileFullPath));
response.BinaryWrite(data);
response.End();
Alert.Show(AlertType.Success, "File downloaded.");
}
catch (Exception ex)
{
logger.Error("Error downloading file from {0}. {1} | {2} | {3}", fileFullPath, ex.Message, ex.StackTrace, ex.InnerException);
Alert.Show(AlertType.Error, string.Format("Error trying to download file: {0}", fileName));
}
}
}
UPDATE:
This is what I came up with in case someone else could use it.
<asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false" CssClass="table borderless" HeaderStyle-CssClass="fileheader">
<Columns>
<asp:BoundField DataField="FileName" HeaderText="File Name" />
<asp:BoundField DataField="FileSize" HeaderText="File Size" />
<asp:BoundField DataField="Date" HeaderText="Created On" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="btnDownload" runat="server"
CommandArgument='<%# Eval("FileName") %>'
OnClick="DownloadFile"
ToolTip="Downloaded file">
<span aria-hidden="true" class="fa fa-download"></span>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
void LoadGrid()
{
// create a table for the files, populate, and then bind.
DataTable dtFiles = new DataTable();
dtFiles.Columns.Add("Date", typeof(string));
dtFiles.Columns.Add("FileSize", typeof(string));
dtFiles.Columns.Add("FileName", typeof(string));
DirectoryInfo fileDirectory = new DirectoryInfo(FileFolderPath);
foreach (FileInfo file in fileDirectory.GetFiles("*.txt"))
{
DataRow dr = dtFiles.NewRow();
dr["Date"] = file.CreationTime.ToString("MM/dd/yyyy HH:mm");
dr["FileSize"] = Utility.GetBytesReadable(file.Length);
dr["FileName"] = file.Name;
dtFiles.Rows.Add(dr);
}
dtFiles.DefaultView.Sort = "Date DESC";
gvFiles.DataSource = dtFiles;
gvFiles.DataBind();
}
protected void DownloadFile(object sender, EventArgs e)
{
var fileName = (sender as LinkButton).CommandArgument;
var fileFullPath = Path.Combine(FileFolderPath, fileName);
string mineType = MimeMapping.GetMimeMapping(fileFullPath);
if (string.IsNullOrWhiteSpace(fileName) == false)
{
byte[] binFile = File.ReadAllBytes(fileFullPath);
Response.ContentType = mineType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(binFile);
Response.End();
}
}
You can say use a gridview, and say like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table">
<Columns>
<asp:BoundField DataField="File Name" HeaderText="File" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="File Size" HeaderText="Size" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" CssClass="btn btn-default"
NavigateUrl='<%# Eval("Path") %>' >Down Load</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And code behind can be this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
// create a table for the files
DataTable MyTable = new DataTable();
MyTable.Columns.Add("Date", typeof(string));
MyTable.Columns.Add("File Size", typeof(string));
MyTable.Columns.Add("File Name", typeof(string));
MyTable.Columns.Add("Path", typeof(string));
string strURLFolder = "~/Content/Animals/";
string strFolder = Server.MapPath(strURLFolder);
DirectoryInfo MyDir = new DirectoryInfo(strFolder);
FileInfo[] MyFiles = MyDir.GetFiles("*.*");
foreach (FileInfo MyFile in MyDir.GetFiles("*.*"))
{
DataRow OneRow = MyTable.NewRow();
OneRow["Date"] = MyFile.LastAccessTime;
OneRow["File Size"] = (MyFile.Length / 1024).ToString() + " KB";
OneRow["File Name"] = MyFile.Name;
OneRow["Path"] = strURLFolder + MyFile.Name;
MyTable.Rows.Add(OneRow);
}
MyTable.DefaultView.Sort = "Date";
GridView1.DataSource = MyTable;
GridView1.DataBind();
}
And now we get this:
Now, I suppose you could replace the "hyper-link" with a button, and perhaps read the files as byte stream, and send that to the client, but above should get you started here.
Edit: The user notes they don't want to use a hyper-link (simple link) to the file.
So, we can do it this way:
We drop in a plane jane button into the grid (why then suggest, hint, talk about a "link" when you NOW stated you DO NOT want to use a link? - are we giving out awards for confusing here?).
If you don't want a link, then obviously we don't need nor want to care about, and talk about links then right?????
Ok, so lets remove the hyper link, and drop in a plane jane button into the grid view like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table">
<Columns>
<asp:BoundField DataField="File Name" HeaderText="File" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="File Size" HeaderText="Size" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdDownLoad" runat="server" Text="Download" cssclass="btn"
OnClick="cmdDownLoad_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So, code to load as before, and now we get/have this:
protected void cmdDownLoad_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
string sFileOnly = gRow.Cells[0].Text;
string sFile = Server.MapPath("~/Content/Animals/" + sFileOnly);
string sMineType = MimeMapping.GetMimeMapping(sFile);
byte[] binFile = File.ReadAllBytes(sFile);
Response.ContentType = sMineType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + sFileOnly);
Response.BinaryWrite(binFile);
Response.End();
}
So, we should see say this:
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();
}
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>
Currently I'm having trouble in update function for DataGrid. It is unable capture my input in the DataGrid.
Is there a way to capture my input by using DataGrid? Because most of the information internet using GridView which is different.
Edited:
This is a DataGrid with Update, Edit and delete function.
For example,
I select a row of data and press on Edit button, fill in the data on the selected row, then press on Update button to update the selected row information.
In this situation I am unable to capture the selected row information after edited.
So, I am unable to update the row data.
Here's the Code for HTML
<asp:DataGrid ID="dgRecords" runat="server" Width="100%" DataKeyField="InsitePriceID"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="5"
OnPageIndexChanged="dgRecords_PageIndexChanged" OnSortCommand="dgRecords_SortCommand"
OnDeleteCommand="dgRecords_OnDelete" OnEditCommand="dgRecords_OnEdit" OnUpdateCommand="dgRecords_OnUpdate"
OnCancelCommand="dgRecords_OnCancel">
<AlternatingItemStyle CssClass="Data"></AlternatingItemStyle>
<ItemStyle CssClass="Data"></ItemStyle>
<HeaderStyle CssClass="ColHeader"></HeaderStyle>
<Columns>
<asp:BoundColumn Visible="False" DataField="InsitePriceID"></asp:BoundColumn>
<asp:BoundColumn DataField="ServicePartFrom" HeaderText="No. of Service Part (From)"
SortExpression="ServicePartFrom"></asp:BoundColumn>
<asp:BoundColumn DataField="ServicePartTo" HeaderText="No. of Service Part (To)"
SortExpression="ServicePartTo"></asp:BoundColumn>
<asp:BoundColumn DataField="BaseAmount" HeaderText="% from Base Amount" SortExpression="BaseAmount">
</asp:BoundColumn>
<asp:EditCommandColumn ButtonType="PushButton" CancelText="Cancel" EditText="Edit"
UpdateText="Update"></asp:EditCommandColumn>
<asp:ButtonColumn ButtonType="PushButton" CommandName="Delete" Text="Delete"></asp:ButtonColumn>
</Columns>
<PagerStyle Mode="NumericPages"></PagerStyle>
</asp:DataGrid>
<td style="width: 1014px">
<asp:Label ID="lbla" runat="server"></asp:Label>
<asp:Label ID="lblb" runat="server"></asp:Label>
<asp:Label ID="lblc" runat="server"></asp:Label>
</td>
Code behind.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ucWScr.SetValue("Insite Price");
pnlMsg.Visible = false;
BindData("");
}
}
private void BindData(string _sortExpression)
{
clsAdmin obj = new clsAdmin();
int intNoRec = 0;
DataTable tbl = obj.SearchInsitePrice();
}
protected void dgRecords_OnUpdate(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Update")
{
string strInsitePriceID = dgRecords.DataKeys[e.Item.ItemIndex].ToString();
//Error start from here
lbla.Text = e.Item.Cells[1].Text;
lblb.Text = e.Item.Cells[2].Text;
lblc.Text = e.Item.Cells[3].Text;
int intServicePartFrm = Int32.Parse(lbla.Text);
int intServicePartTo = Int32.Parse(lblb.Text);
int fltPercentBaseAmt = Int32.Parse(lblc.Text);
//Error ends here
string strUserLogin = CurrentUser.UserLogin.ToString();
DateTime dteNow = DateTime.Now;
if (strInsitePriceID != "")
{
EStatus status = webform.UpdateInsitePrice(strInsitePriceID, intServicePartFrm, intServicePartTo, fltPercentBaseAmt, strUserLogin, dteNow);
if (status != EStatus.Success) throw new Exception("Update failed.");
I solve the problem by using this method.
protected void dgRecords_OnUpdate(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Update")
{
string strInsitePriceID = dgRecords.DataKeys[e.Item.ItemIndex].ToString();
TextBox temp, temp2, temp3;
temp = (TextBox)e.Item.Cells[1].Controls[0];
temp2 = (TextBox)e.Item.Cells[2].Controls[0];
temp3 = (TextBox)e.Item.Cells[3].Controls[0];
int intServicePartFrm = Int32.Parse(temp.Text);
int intServicePartTo = Int32.Parse(temp2.Text);
int fltPercentBaseAmt = Int32.Parse(temp3.Text);