Trying to get checkbox checked rows values from gridview using Javascript - javascript

I have gridview with checkbox as first column and I am trying to get the selected checkbox complete row values using Javascript function attached to check box mentioned below.
I tried with the different approach but got stuck in middle that is why I posted here again.
But some how I am not getting inside to the for loop and I am not sure where I am getting error in this code.
Javascript function:
function checkForVirtual(){
var GridView = document.getElementById('<%=gvPRCertInfo.ClientID %>');
if (GridView.rows.length > 0) {
alert('check');
for (Row = 1; Row < GridView.rows.length; Row++) {
alert("check 2 times");
if (GridView.rows[Row].cell[1].type == "checkbox") {
/// not getting into this
/// alert is not firing even if the checkbox is there
alert('inside');
if (GridView.rows[Row].cell[0].childNodes[0].checked) {
alert('checked');
var type = GridView.rows[Row].cell[3].childNodes[0].val();
alert(type);
}
}
}
}
}
This is my grid view:
<asp:GridView ID="gvPRCertInfo" runat="server" AutoGenerateColumns="False" GridLines="None"
OnRowDataBound="gvPRCertInfo_RowDataBound"
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" OnCheckedChanged="chkCert_CheckedChanged" OnClick="Javascript:checkForVirtual();" 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" />
<asp:BoundField DataField="partID" HeaderText="Part Number" HeaderStyle-HorizontalAlign="Center" />
..............................
</Columns>
.........................
.......................
</asp:GridView>
Would any one please help on this one?

<HeaderTemplate>
<asp:CheckBox ID="chkboxSelectAll" AutoPostBack="true" OnCheckedChanged="chkboxSelectAll_CheckedChanged" runat="server" Text="All" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkCert" runat="server" Font-Size="XX-Small" />
</ItemTemplate>
</asp:TemplateField>
in cs file
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox chckheader = (CheckBox)gvPRCertInfo.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in gvPRCertInfo.Rows)
{
CheckBox CheckBoxchckrw = (CheckBox)row.FindControl("chkCert");
if (chckheader.Checked == true)
{
CheckBoxchckrw.Checked = true;
}
else
{
CheckBoxchckrw.Checked = false;
}
}
}
get details on button click
protected void button_Click(object sender, EventArgs e)
{
try
{
int cnt = 0;
DataTable dt = new DataTable();
dt.Columns.Add("Certificate ID");
dt.Columns.Add("Part Number");
dt.Columns.Add("Part Description");
foreach (GridViewRow row in gvPRCertInfo.Rows)
{
if ((row.Cells[0].FindControl("chkCert") as CheckBox).Checked)
{
DataRow dr = dt.NewRow();
dr["Certificate ID"] = row.Cells[1].Text;
dr["Part Number"] = row.Cells[2].Text;
dr["Part Description"] = row.Cells[3].Text;
dt.Rows.Add(dr);
cnt++;
}
}
if (cnt <= 0)
{
DataRow dr = dt.NewRow();
dr["Certificate ID"] = gvPRCertInfo.SelectedRow.Cells[1].Text;
dr["Part Number"] = gvPRCertInfo.SelectedRow.Cells[2].Text;
dr["Part Description"] = gvPRCertInfo.SelectedRow.Cells[3].Text;
dt.Rows.Add(dr);
}
Session["Details"] = dt;
Response.Redirect("url");
}
catch (Exception ex)
{
}
}
your question is possibly copy of https://stackoverflow.com/a/47478969/8905879

Related

How to get JavaScript variable value in C# code behind

I have a gridview with a column with customised button.
When I click the button, user contact is asked for through JavaScript and then the contact is passed on to rowCommand event of gridview for some operation.
I am using Hiddenfield as a gridview column but there is something going wrong in setting and getting the value.
JavaScript code:
<script type="text/javascript">
function validateContact()
{
var contact = prompt("Please enter your contact number.");
if (isEmpty(contact) && !isNumber(contact) && contact.length != 10)
alert("Invalid contact.");
return;
else
document.getElementById("hiddenCustomerContact.ClientID").value = contact;
}
</script>
asp code:
<asp:GridView ID="gridSearchWorker" runat="server" AutoGenerateColumns="false" OnRowCommand="gridSearchWorker_OnRowCommand" OnRowDataBound="gridSearchWorker_RowDataBound">
<Columns>
<asp:BoundField DataField="WORKER" HeaderText="WORKER" SortExpression="WORKER">
<ItemStyle Width="12%" />
</asp:BoundField>
<asp:TemplateField HeaderText = "" ItemStyle-Width="5%">
<ItemTemplate>
<asp:Button ID="btnGetContact" runat="server" Text="Get Contact" CommandName="GetContact" OnClientClick="validateContact();" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CONTACT" HeaderText="CONTACT" SortExpression="CONTACT">
<ItemStyle Width="12%" />
</asp:BoundField>
<asp:TemplateField HeaderText = "" ItemStyle-Width="5%">
<ItemTemplate>
<asp:HiddenField ID="hiddenCustomerContact" runat="server"/>
</ItemTemplate>
<ItemStyle Width="0.0001%" />
</asp:TemplateField>
</Columns>
</asp:GridView>
c# code behind:
protected void gridSearchWorker_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "GetContact")
{
OleDbConnection conn = new OleDbConnection(cs);
//ask for contact and check if any feedback pending
HiddenField hiddenCustomerContact =
e.Row.FindControl("hiddenCustomerContact") as HiddenField; //getting error in this line
string score = hiddenCustomerContact.Value;
int n = Int32.TryParse(score, out val);
string customerContact = "";
//check if any feedback pending
int pendingCount;
if (pendingCount > 0)
{
//ask to give feedback
}
else
{
//show worker contact
}
}
}
Hi it should work like this:
you can assign some value to the hidden variable as
<script type="text/javascript">
var somefunction = function () {
var hdnfldVariable = document.getElementById('hdnfldVariable');
hdnfldVariable.value = 'value from javascript';
}
</script>
in code behind you can read this field variable:
string variable = hdnfldVariable.Value;

GridView Set ComboBox value Client side

I have a GridView with the following columns.
Parent ID - Bound Column
Child ID - Bound Column
Desc - Bound Column
Status as ComboBox with Values of YES, NO
Parent ID has Child IDs. If i Select Parent ID combobox as YES then all child values should be populated as YES.
I want to do it on Client side using Java Script. Can you please guide me.
<asp:datagrid id="dgImpact" runat="server" Width="78%" CellSpacing="0" AlternatingItemStyle-Height="20px"
AutoGenerateColumns="False" BorderColor="#3A6EA5" ItemStyle-ForeColor="blue"
CellPadding="0" BorderWidth="0px">
<AlternatingItemStyle Height="20px" BackColor="#EEF5FB"></AlternatingItemStyle>
<ItemStyle Height="20px" ForeColor="DarkBlue" BackColor="#DCEDF9"></ItemStyle>
<HeaderStyle Font-Names="Estrangelo Edessa" Font-Bold="True" Wrap="False" ForeColor="White" BorderColor="#336491"
BackColor="#336491"></HeaderStyle>
<Columns>
<asp:ButtonColumn>
<ItemStyle Width="20px"></ItemStyle>
</asp:ButtonColumn>
<asp:ButtonColumn>
<ItemStyle Width="20px"></ItemStyle>
</asp:ButtonColumn>
<asp:ButtonColumn>
<ItemStyle Width="20px"></ItemStyle>
</asp:ButtonColumn>
<asp:BoundColumn Visible="False" DataField="QuestionID" ReadOnly="True">
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Left"></ItemStyle>
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="Questions">
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
<ItemStyle Width="320px"></ItemStyle>
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.QuestionDesc") %>' ID="Label1">
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Status">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<asp:dropdownlist CssClass="ComboStyle" Visible="True" Runat="server" ID="cmbAnswers" Width="72px" SelectedValue='<%# Bind("Status") %>'
DataSource='<%# (new string[] { "--Select--","Yes", "No", "NA","Unknown" }) %>'></asp:dropdownlist>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
.CS
protected void Page_Load(object sender, EventArgs e)
{
DataSet dstQuesData = getRiskDisciplineQuestionAnswer();
dgImpact.DataSource = dstQuesData;
dgImpact.DataBind();
DataTable dtFinalTable = dstQuesData.Tables[0];
for (int intRowCount = 0; intRowCount <= dgImpact.Items.Count - 1; intRowCount++)
{
long a = Convert.ToInt64(dtFinalTable.Rows[intRowCount][9]);
/// 'If the Question Display is root
if (a.ToString().Length == 3)
{
((DataGridItem)dgImpact.Items[intRowCount]).Cells[4].ColumnSpan = 4;
dgImpact.Items[intRowCount].Cells[0].Visible = false;
dgImpact.Items[intRowCount].Cells[1].Visible = false;
dgImpact.Items[intRowCount].Cells[2].Visible = false;
//If the Question Displayed is at Level 1
}
else if (a.ToString().Length == 6 )
{
((DataGridItem)dgImpact.Items[intRowCount]).Cells[4].ColumnSpan = 3;
dgImpact.Items[intRowCount].Cells[0].Visible = true ;
dgImpact.Items[intRowCount].Cells[1].Visible = false;
dgImpact.Items[intRowCount].Cells[2].Visible = false;
//If the Question Displayed is at Level 2
}
else if (a.ToString().Length == 9)
{
((DataGridItem)dgImpact.Items[intRowCount]).Cells[4].ColumnSpan = 2;
dgImpact.Items[intRowCount].Cells[0].Visible = true;
dgImpact.Items[intRowCount].Cells[1].Visible = true;
dgImpact.Items[intRowCount].Cells[2].Visible = false;
}
else if (a.ToString().Length == 12)
{
((DataGridItem)dgImpact.Items[intRowCount]).Cells[4].ColumnSpan = 1;
dgImpact.Items[intRowCount].Cells[0].Visible = true;
dgImpact.Items[intRowCount].Cells[1].Visible = true;
dgImpact.Items[intRowCount].Cells[2].Visible = true;
}
}
}
public DataSet getRiskDisciplineQuestionAnswer()
{
DataSet riskQuestionAnswerData = new DataSet();
sqlConnection = new SqlConnection(connStr);
sqlCommand = new SqlCommand("usp_testRDD1", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlDataAdapter = new SqlDataAdapter(sqlCommand);
try
{
sqlDataAdapter.Fill(riskQuestionAnswerData);
}
catch
{
throw;
}
return riskQuestionAnswerData;
}
Couldn't find a proper solution for you problem.
Please take a look at this Link. i hope this will help.

getElementByID for templateField TextBox

i have used RowDataBound for gridview. Below is my C# code
protected void gvParameterValue_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblLocID = (Label)e.Row.FindControl("lblLocationID");
if(condition)
{
TextBox txtBox = (TextBox)e.Row.FindControl("txtValue");
txtBox.Attributes.Add("onchange", "ValueOnChange();");
}
}
}
Asp.Net code for gridview
<asp:UpdatePanel ID="updatePanel" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="gvParameterValue" SkinID="GridView" runat="server" OnRowDataBound ="gvParameterValue_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Location Name">
<asp:TemplateField HeaderText="Parameter Value">
<ItemTemplate>
<asp:TextBox ID="txtValue" SkinID="fineLineTextBox" TabIndex="1" runat="server" AutoPostBack="false"></asp:TextBox>
<%--<asp:TextBox ID="TextBox1" SkinID="fineLineTextBox" TabIndex="1" runat="server" OnTextChanged="textBox1_textChanged" AutoPostBack="true"></asp:TextBox>--%>
<asp:Label ID="lblPreDayVal" runat="server" Text='<%# Bind("PreviousValue") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate >
</asp:UpdatePanel>
js function as below and i have a problem
function ValueOnChange()
{
var val = document.getElementById('lblPreDayValue').value;
}
It gives error "Microsoft JScript runtime error: Object required"
i have tried all possible solutions from net but nothing works...
You've called getElementById on the ID lblPreDayValue. In your ASP.NET markup you've called it lblPreDayVal.
You might also want to use ClientID to ensure you get the correct ID generated by .NET
You can pass the ClientID from the server-side during the binding step in the gvParameterValue_RowDataBound method like this :-
TextBox txtBox = (TextBox)e.Row.FindControl("txtValue");
Label lblVal = (Label)e.Row.FindControl("lblPreDayVal");
txtBox.Attributes.Add("onchange", "ValueOnChange('" + lblVal.ClientID + "');");
And then inside the ValueOnChange method definition, pass the argument as cid (lets say).
function ValueOnChange(cid)
{
var val = document.getElementById(cid).innerHTML;
}
Try passing values at the RowBound event of gridview , You are trying to access getElementbyId('lblLocID') is not going to work because it's id will be change when row renders .
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblLocID = (Label)e.Row.FindControl("lblLocationID");
Label lblPreDayValue =(Label)e.Row.FindControl("lblPreDayValue");
if (lblLocID.Text.Equals("154") || lblLocID.Text.Equals("168") || lblLocID.Text.Equals("178"))
{
TextBox txtBox = (TextBox)e.Row.FindControl("txtValue");
txtBox.Attributes.Add("onchange", "ValueOnChange(" + lblPreDayValue.ClientID + ");");
}
}
After passing ClientID to function
//Or you can directly pass the value of label and assign .
function ValueOnChange(ClntID)
{
var val = document.getElementById('ClntID').innerHTML;
}
Try to use
function ValueOnChange()
{
var val = document.getElementById('#<%= lblPreDayVal.ClientID %>').innerHTML;
}
If the above din work then
function ValueOnChange()
{
var val = document.getElementById('lblPreDayVal').innerHTML;
}

Adding new rows dynamically in a grid view or datatable in asp.net?

I am binding the grid view using data table.
My task is to add new rows to my grid view dynamically when the user clicks "ADD" button in grid view it should generate new row with three text boxes.
For example: When I click the add button in the second row, a new row should be created below the second row with three text box where the user can enter details.
Can anybody help me resolve this problem? Either in jQuery/JavaScript or on the server side.
you could try this solution
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
inside code behind
Here’s the code block below:
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", 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["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
in page load you have to call this method
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
this is the method for generating the rows when clicking the Button. Here are the code blocks below:
private void AddNewRowToGrid()
{
int rowIndex =0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
drCurrentRow["Column3"] = box3.Text;
rowIndex++;
}
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState
ViewState["CurrentTable"] = dtCurrentTable;
//Rebind the Grid with the current data
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
this is setpreviousdata method...
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 1; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
button click event for adding new row
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
and pls take a look below image how it will generate new rows....
I hope it will helps you.....
You can use fnOpen http://www.datatables.net/ref#fnOpen. It will let you add a row directly below the row you give it. you can give that new row the html you want it to have as well.

Enable/disable text box placed in gridview on check event of check box with javascript

I have gridview which contains check box and textbox in different item template fields. Text boxes will be disbled when grid is loaded. Now what I want is, when user checks any of the check box, respected textbox in that particular row should be enabled. When user unchecks the checked checkbox, again the textbox should get clear and disable. Now when user clicks on the save button, a javascript should validate all the textbox whose respected checkboxes are checked.
Validation is
(1)Text boxes should not be empty
(2)It should allow only character and space(I want to enter name in that text box). How can I write java script to perform all this task. I am novice to javascript and completely unaware of its concept.
Thanks in advance
<script type="text/javascript">
var nameRegex = /^[a-zA-Z ]+$/;
function validateName(sender, args) {
args.IsValid = nameRegex.test(args.Value);
}
</script>
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false" DataKeyNames="Id" >
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" OnCheckedChanged="SelectRow" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:TemplateField HeaderText="Name" >
<ItemTemplate>
<asp:TextBox runat="server" ID="NameTextBox" Enabled="false" Text='<%# Eval("Name") %>' />
<asp:CustomValidator runat="server" ID="NameValidator" ControlToValidate="NameTextBox"
ValidateEmptyText="true" Text="!" Display="Static" Enabled="false"
ClientValidationFunction="validateName" OnServerValidate="ValidateName" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public partial class WebForm1 : System.Web.UI.Page
{
private static readonly Regex nameRegex = new Regex("^[a-zA-Z ]+$");
protected void ValidateName(object source, ServerValidateEventArgs args)
{
args.IsValid = nameRegex.IsMatch(args.Value);
}
protected void SelectRow(object sender, EventArgs e)
{
Page.Validate();
var checkBox = (CheckBox)sender;
if (Page.IsValid || !checkBox.Checked)
{
var textBox = (TextBox)checkBox.NamingContainer.FindControl("NameTextBox");
var nameValidator = (CustomValidator)checkBox.NamingContainer.FindControl("NameValidator");
textBox.Enabled = checkBox.Checked;
nameValidator.Enabled = checkBox.Checked;
if (!checkBox.Checked)
textBox.Text = "";
}
else
{
checkBox.Checked = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = from item in Enumerable.Range(0, 10)
select new
{
Id = item,
Name = ""
};
GridView1.DataBind();
}
}
}

Categories