I cannot figure out how to make this situation. I have ASP.NET application with webpage showing GridView linked to database - showing books which can be rented. I want to have button at each line, so user can click and rent this book. After click, user should get messageBox with question like "Do you really want to rent this book? and Yes/No option and in c# code I want to gent this answer with line, where this button was clicked and handle it properly.
So far I was able to create this code :
GridView :
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1" EmptyDataText="Žádné datové záznamy k zobrazení." OnRowCommand="GridView2_RowCommand">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="author" HeaderText="author" SortExpression="author" />
<asp:BoundField DataField="genre" HeaderText="genre" SortExpression="genre" />
<asp:BoundField DataField="availability" HeaderText="availability" SortExpression="availability" />
<asp:BoundField DataField="owner" HeaderText="owner" SortExpression="owner" />
<asp:BoundField DataField="isbn" HeaderText="isbn" SortExpression="isbn" />
<asp:BoundField DataField="barcode" HeaderText="barcode" SortExpression="barcode" />
<asp:BoundField DataField="amount" HeaderText="amount" SortExpression="amount" />
<asp:ButtonField CommandName="text" Text="button" />
</Columns>
</asp:GridView>
Script to handle question :
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to rent this book?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
and in my C# code I have
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "text")
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
showMessage("You clicked YES!");
}
else
{
showMessage("You clicked NO!");
}
//GridView2.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Text); -> cell value of clicked row
}
}
private void showMessage(string text)
{
string script = "alert(\"" + text + "\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
But I cannot figure out, how to add script to gridView button, any help?
You can use OnClientClick for that
<asp:ButtonField CommandName="text" Text="button" OnClientClick="return Confirm();"/>
And Your javascript function look like
<script type = "text/javascript">
function Confirm() {
if (confirm("Do you want to rent this book?")) {
return true;
} else {
return false;
}
}
</script>
No need to store value in hidden field because if user click on 'No' then page won't post back.
Just figured out how to do it by myself, button needs to be transfered to templateField and then it´s possible to add onClientClick
Related
I have below function when we check or uncheck the check box (inside the gridview) it will show the popup and other processing information.
Is there any way to execute this function only when checkbox is checked and not on unchecked condition?
Below is my function:
$(document).ready(function () {
$('#<%= gvPRCertInfo.ClientID %> input[type="checkbox"]').change(function () {
var signValue = $(this).closest('tr').children('td:eq(4)').html();
if (signValue == "Virtual") {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("you have selected virtual do u want to create a new name for this?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
});
});
This is my gridview:
<asp:GridView ID="gvPRCertInfo" runat="server" GridLines="None"
CssClass="data responsive">
<Columns>
<asp:TemplateField HeaderText="Select" SortExpression="">
<HeaderTemplate>
<asp:CheckBox ID="chkboxSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkboxSelectAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkCert" AutoPostBack="true" ClientIDMode="Static" OnCheckedChanged="chkCert_CheckedChanged" runat="server" />
<input type="hidden" id="hdnCertId" runat="server" value='<%# DataBinder.Eval(Container.DataItem, "CertId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CertificateID" HeaderText="Certificate ID" HeaderStyle-HorizontalAlign="Center" />
................
.................
Would anyone please suggest any ideas on how to execute only when I check the checkbox.
Try this inside the on change function of the checkbox.
if($(this).is(':checked') == true)
{
/* Your function code here.*/
}
hello my dear i think this will work but still i'm not sure
you can code like below :
$(document).ready(function () {
$('#myCheckbox').change(function () {
if ($(this).attr("checked")) {
// fire your function
return;
}
// not checked
});
});
try this in side the onchange function
Javascript code
if(document.getElementById('mycheckbox').checked) {
console.log("ckecked")
} else {
console.log("not ckecked")
}
jquery code
if ($('#mycheckbox').attr("checked")) {
console.log("ckecked")
}else{
console.log("not ckecked")
}
You can use jQuery's is() function:
if($("input").is(':checked')) {
dosomething
}
I have got a problem with making textbox empty using JavaScript function.
If checkbox is unchecked the asp:Textbox should make disabled and empty.
It happens, but in code behind all the time is visible previous value which was entered before in that textbox.
<asp:RadioButton ID="radio_fx_no" runat="server" Text="NO" GroupName="optradio1" onclick="CheckBoxChangedDisableFx(this);" />
<asp:RadioButton ID="radio_fx" runat="server" Text="YES" GroupName="optradio1" onclick="CheckBoxChangedAbleFx(this);" />
<asp:TextBox ID="txt_fx" ClientIDMode="Static" runat="server" Enabled="false" />
<script>
function CheckBoxChangedAbleFx(checkbox) {
if (checkbox.checked == true) {
document.getElementById('<%= txt_fx.ClientID %>').disabled = false;
}
}
function CheckBoxChangedDisableFx(checkbox) {
if (checkbox.checked == true) {
document.getElementById('<%= txt_fx.ClientID %>').value = "";
document.getElementById('<%= txt_fx.ClientID %>').disabled = true;
}
}
</script>
Any ideas what is wrong in my code?
This problem is called the Cacheing the browser data. You can try three things in this case:
1) Clear value of textbox in pageload event at every postback:
if (IsPostBack)
{
txt_fx.text = "";
}
and in your aspx code make text="":
<asp:TextBox ID="txt_fx" Text="".../>
2) Set AutoComplete property of textbox to off for html input
or disable autocompletetype property of asp textbox
<asp:TextBox ID="txt_fx" autocompletetype="disabled".../>
3) or Set AutoComplete of your FORM tag of your page to "off"
If you want to clear actual value of textbox on server side without postback then you need to use AJAX.
Hope it will help you..!!
in .cs file,Page_Load method,plus such code:
if(!Page.IsPostBack)
{
radio_fx.Attributes.Add("onClick", "return CheckBoxChangedState(this,false);");
radio_fx_no.Attributes.Add("onClick", "return CheckBoxChangedState(this,true);");
}
and in .aspx file,change as follows:
<script type="text/javascript">
function CheckBoxChangedState(checkbox, state) {
if (checkbox.checked == true) {
document.getElementById('<%= txt_fx.ClientID %>').value = "";
document.getElementById('<%= txt_fx.ClientID %>').disabled = state;
}
}
<asp:RadioButton ID="radio_fx_no" runat="server" AutoPostBack="false" Text="NO" GroupName="optradio1" />
<asp:RadioButton ID="radio_fx" runat="server" AutoPostBack="false" Text="YES" GroupName="optradio1" />
I have a grid view in asp.net as given below.
<asp:GridView ID="grid_flats_allflatslist" OnRowDeleting="grid_flats_allflatslist_RowDeleting" runat="server" Width="95%" CssClass="gridview" ShowFooter="true" AllowPaging="true" PageSize="8" BackColor="Black" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="1" CellSpacing="1" frame="below" DataKeyNames="BlockID" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="BlockID" HeaderText="Block ID" Visible="false" />
<asp:BoundField DataField="BlockName" HeaderText="Block Name" />
<asp:TemplateField HeaderText="Flat Number">
<ItemTemplate>
<asp:TextBox ID="text_flats_listflatnumber" CssClass="textbox" onkeypress="return numeric(this);" MaxLength="5" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Flat Number">
<ItemTemplate>
<asp:DropDownList ID="list_flats_listflattype" CssClass="droplist" runat="server">
<asp:ListItem Text="Bachelor" Value="Bachelor"></asp:ListItem>
<asp:ListItem Text="Family" Value="Family"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Max Vacancy">
<ItemTemplate>
<asp:TextBox ID="text_flats_listmaxvacancy" onkeypress="return numeric(this);" MaxLength="2" CssClass="textbox" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="true" DeleteText="Delete" />
</Columns>
<FooterStyle BackColor="#9e4900" ForeColor="#fff1e5" Font-Bold="false" Font-Underline="false" HorizontalAlign="Center" />
<HeaderStyle BackColor="#9e4900" ForeColor="#fff1e5" HorizontalAlign="Center" />
<PagerStyle BackColor="#ff8080" ForeColor="#660000" HorizontalAlign="Right" />
<RowStyle BackColor="#ffe7d6" ForeColor="#660000" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="#ffd6ba" ForeColor="#660000" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#fff9f4" HorizontalAlign="Center" ForeColor="Black" />
</asp:GridView>
<asp:Button ID="button_flats_flatplus" CssClass="button" Height="30px" Width="25%" runat="server" Text="Add Flat" OnClick="button_flats_flatplus_Click" />
Initially, this is empty and when I click on the button_flats_flatsplus button then a row will be added to the grid view with the field as above. It will also have 2 text boxes and a drop-down list. The button click event is as below.
protected void button_flats_flatplus_Click(object sender, EventArgs e)
{
DataTable dt;
DataRow dr = null;
if (ViewState["CurrentTable"] == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("BlockID", typeof(string)));
dt.Columns.Add(new DataColumn("BlockName", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["BlockID"] = list_flats_blocklist.SelectedValue; // I get this value from a different list
dr["BlockName"] = list_flats_blocklist.SelectedItem.Text; // I get this value from a different list
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
grid_flats_allflatslist.DataSource = dt;
grid_flats_allflatslist.DataBind();
}
else
{
dt = (DataTable) ViewState["CurrentTable"];
dr = dt.NewRow();
dr["BlockID"] = list_flats_blocklist.SelectedValue; // I get this value from a different list
dr["BlockName"] = list_flats_blocklist.SelectedItem.Text; // I get this value from a different list
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
grid_flats_allflatslist.DataSource = dt;
grid_flats_allflatslist.DataBind();
}
SetPreviousData();
}
After I add many rows the grid view will look as below,
If I press delete then that particular row it is getting deleted successfully but the values in all the other rows are cleared. My row deleting code is as below with the SetPreviousData function but it won't work.
protected void grid_flats_allflatslist_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["CurrentTable"] as DataTable;
dt.Rows[index].Delete();
ViewState["CurrentTable"] = dt;
grid_flats_allflatslist.DataSource = dt;
grid_flats_allflatslist.DataBind();
SetPreviousData();
}
Everytime I add a new row to the grid view or delete a row from the grid view, post back happens and whatever values I have entered into the text boxes and drop-down list of other rows gets cleared. I tried to handle this with !Page.IsPostBack but still not working.
Then I tried the following code and added it to all the places that had a postback or data bind to the grid view.
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)grid_flats_allflatslist.Rows[rowIndex].Cells[3].FindControl("text_flats_listflatnumber");
DropDownList box2 = (DropDownList)grid_flats_allflatslist.Rows[rowIndex].Cells[4].FindControl("list_flats_listflattype");
TextBox box3 = (TextBox)grid_flats_allflatslist.Rows[rowIndex].Cells[5].FindControl("text_flats_listmaxvacancy");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.SelectedValue = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
If I try to add !Page.IsPostBack in the grid vide bind then whatever changes I make to grid view, add or delete rows is not getting reflected. How can I avoid clearing of the text boxes in grid view whenever there is a post back or data bind on the page? I still want to delete and add rows to grid view by still keeping the already entered values in the fields.
I have tested your code, and it works just fine.
You may not defined the ViewState["CurrentTable"] properly. This is what i added to your code:
public DataTable CurrentTable
{
get
{
return (DataTable)ViewState["CurrentTable"];
}
set
{
ViewState["CurrentTable"] = value;
}
}
*A GIF to describe how it works.
EDIT
I would suggest the following in order to be able to keep the data on the gridview :
ViewState List should have the values:
public class CustomDataTable
{
public int BlockID { get; set; }
public string BlockName { get; set; }
public string Column1 { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
}
And its property :
public List<CustomDataTable> CurrentTable
{
get
{
return (List<CustomDataTable>)ViewState["CurrentTable"];
}
set
{
ViewState["CurrentTable"] = value;
}
}
In the Picture below;
What Add Flat button should do is to populate a new default row into the gridview.
Whenever Save button clicked , it should store that row data into
the CurrentTable.
Whenever Delete button clicked , it should Remove that row from
the CurrentTable.
I am trying to Search records from gridview with pagination, matching with the values entered into textbox, and its working quite fine. Issue is that it only show the records which are at first page , but not search the records from the next pages.
aspx code:
<asp:GridView ID="GrdFutureApt" AutoGenerateColumns="false" runat="server" CssClass="table table-responsive table-condensed table-bordered table-striped" AllowPaging="true"
CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="5" OnPageIndexChanging="GrdFutureApt_PageIndexChanging">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientName" HeaderText="Patient Name" Visible="false"/>
<asp:BoundField DataField="DoctorName" HeaderText="Doctor Name"/>
<asp:BoundField DataField="AppointmentDate" HeaderText="Appointment Date" DataFormatString="{0:dd/MM/yyyy}"/>
<asp:TemplateField HeaderText = "Appointment Time" SortExpression="Time">
<ItemTemplate>
<asp:Label runat="server" ID="lblAppointmentTime" Text='<%# DisplayAs12HourTime(Eval("AppointmentTime")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AppoinmentStatus" HeaderText="Status"/>
</Columns>
<PagerSettings Mode="NextPrevious" PreviousPageText="Previous" NextPageText=" Next" Position="Bottom" />
<PagerStyle BackColor="#889FA2" HorizontalAlign="Left" ForeColor="White" Font-Bold="true" />
</asp:GridView>
I have used Following script to perform this function.
<script type="text/javascript">
$(document).ready(function () {
$('#<%=txtSearchBox.ClientID %>').keyup(function (e) {
SearchGridData();
});
});
function SearchGridData() {
var counter = 0;
//Get the search text
var searchText = $('#<%=txtSearchBox.ClientID %>').val().toLowerCase();
//Hide No record found message
$('#<%=lblMsgFail.ClientID %>').hide();
//Hode all the rows of gridview
$('#<%=GrdAppointments.ClientID %> tr:has(td)').hide();
if (searchText.length > 0) {
//Iterate all the td of all rows
$('#<%=GrdAppointments.ClientID %> tr:has(td)').children().each(function () {
var cellTextValue = $(this).text().toLowerCase();
//Check that text is matches or not
if (cellTextValue.indexOf(searchText) >= 0) {
$(this).parent().show();
counter++;
}
});
if (counter == 0) {
//Show No record found message
$('#<%=lblErrorMsg.ClientID %>').show();
}
}
else {
//Show All the rows of gridview
$('#<%=lblErrorMsg.ClientID %>').hide();
$('#<%=GrdAppointments.ClientID %> tr:has(td)').show();
}
}
</script>
And using following javascript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
the data to fill gridview comes from the following function:
public void LoadGrid()
{
S011AppointmentBOL objBol = new S011AppointmentBOL();
//DataTable ptApt = new DataTable();
dtAppointment = S011AppointmentBLL.GetAll();
int patID = dtPatient.AsEnumerable().Where(x => x.Field<string>("RegistrationNo") == RegNo).Select(x => x.Field<int>("PatientID")).FirstOrDefault();
dtAppointment.Columns.Add("PatientName", typeof(string));
dtAppointment.Columns.Add("DoctorName", typeof(string));
for (int i = 0; i < dtAppointment.Rows.Count; i++)
{
string pFname = dtPatient.AsEnumerable()
.Where(x => x.Field<int>("PatientID") == Convert.ToInt32(dtAppointment.Rows[i]["PatientID"]))
.Select(x => x.Field<string>("FirstName")).FirstOrDefault();
string pLname = dtPatient.AsEnumerable()
.Where(x => x.Field<int>("PatientID") == Convert.ToInt32(dtAppointment.Rows[i]["PatientID"]))
.Select(x => x.Field<string>("LastName")).FirstOrDefault();
string dFname = dtDoctor.AsEnumerable()
.Where(x => x.Field<int>("DoctorID") == Convert.ToInt32(dtAppointment.Rows[i]["DoctorID"]))
.Select(x => x.Field<string>("FirstName")).FirstOrDefault();
string dLname = dtDoctor.AsEnumerable()
.Where(x => x.Field<int>("DoctorID") == Convert.ToInt32(dtAppointment.Rows[i]["DoctorID"]))
.Select(x => x.Field<string>("LastName")).FirstOrDefault();
dtAppointment.Rows[i]["PatientName"] = pFname + " " + pLname;
dtAppointment.Rows[i]["DoctorName"] = dFname + " " + dLname;
}
DataTable boundTable = new DataTable();
var query = dtAppointment.AsEnumerable().Where(x => x.Field<int>("PatientID") == patID).Select(x => x).OrderByDescending(x => x.Field<DateTime>("AppointmentDate"));
var t = query.Any();
if (t)
{
boundTable = query.CopyToDataTable<DataRow>();
}
GrdAppointments.DataSource = boundTable;
GrdAppointments.DataBind();
}
And On every keyup I don't want query to database that's why am using the Datatable to fill gridview
Any Help Appreciated.. Thanks
You have enabled paging for Gridview so it will bind only records from selected pages on client side.So you have to either disable paging or rewrite jquery search function by calling a webmethord to search entire records which can bind search results.
I have asp.net form having 4 check boxes. not check box list. these 4 check boxes having the ValidationGroup property with same name say "chkValied". I have added Custom Validator there. now want to check at least on check box should be check out of these. what to do ?
You can use CustomValidator to validate input at client-side or server-side code.
aspx markup
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:CheckBox ID="CheckBox3" runat="server" />
<asp:CheckBox ID="CheckBox4" runat="server" />
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ErrorMessage="put here error description"
ClientValidationFunction="clientfunc"
OnServerValidate="CheckValidate">
</asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
.cs (code-behind)
protected void CheckValidate(object source, ServerValidateEventArgs args)
{
args.IsValid=false;
if (CheckBox1.Checked)
args.IsValid = true;
if (CheckBox2.Checked)
args.IsValid = true;
if (CheckBox3.Checked)
args.IsValid = true;
if (CheckBox4.Checked)
args.IsValid = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (IsValid)
{
//valid
}
else
{
//Invalid
}
}
JavaScript code
<script type="text/javascript">
function clientfunc(sender, args) {
args.IsValid = false;
if (document.getElementById("CheckBox1").checked)
args.IsValid = true;
if (document.getElementById("CheckBox2").checked)
args.IsValid = true;
if (document.getElementById("CheckBox3").checked)
args.IsValid = true;
if (document.getElementById("CheckBox4").checked)
args.IsValid = true;
}
</script>
Try this article
http://weblogs.asp.net/samirgeorge/archive/2009/05/02/checkboxlist-client-side-validation-using-jquery.aspx
https://web.archive.org/web/20211020153246/https://www.4guysfromrolla.com/webtech/tips/t040302-1.shtml
If you are using custom validator such thing could be achieved with an or-statement:
if (chkBox1.Checked || chkBox2.Checked || chkBox3.Checked)
{
// At least 1 checkbox was checked.
}
This applies to all languages (although || is not universal all languages has a representation of it). In JavaScript you'd want .Value instead of .Checked.