Essentially trying to capture information when a checkbox is checked off, if it is then capture the quantity inputted. Attached is the code.
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextboxQuantity" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Here is my aspx.cs code.
//check to see if a check box is checked
for (int row = 0; row < gv_Input.Rows.Count; row++)
{
CheckBox Cbox = (CheckBox)gv_Input.Rows[row].FindControl("CheckboxSelect");
TextBox Tbox = (TextBox)gv_Input.Rows[row].FindControl("TextboxQuantity");
int quantity = Convert.ToInt32(Tbox.Text);
if (Cbox.Checked)
{
if (Tbox == null)
{
Response.Write("<script>alert('Fill in textbox')</script>");
}
else
{
Response.Write(
"<script>alert('Something was inputted into the textbox')</script>");
}
}
}
The line that gives the error is this line
int quantity = Convert.ToInt32(Tbox.Text);
Error:
Input string was not in the correct format
Even if the text box is left blank, the test if (Tbox == null) is never going to be true because you are checking the reference to the text box, not its content. I believe that your test should be:
if(Tbox == null || string.IsNullOrWhitespace(Tbox.Text) == true) {
Through further testing. I attempted using a foreach loop and it seemed to work. Thank you for you help here is my solution
foreach (GridViewRow row in gv_Input.Rows)
{
CheckBox Cbox = (CheckBox)row.FindControl("CheckboxSelect");
TextBox Tbox = (TextBox)row.FindControl("TextboxQuantity");
if (Cbox.Checked)
{
if (Tbox.Text == null || string.IsNullOrEmpty(Tbox.Text) == true)
{
Response.Write("<script>alert('Fill in textbox')</script>");
}
else {
Response.Write("<script>alert('Successful find')</script>");
}
Related
i have created a telerik grid for small payment module
in this module i have selected two checkbox and enter a amount,i need the total amount to be displayed in the donation amount label
The current code is to sum up the values displayed in the second column,and saving the values in session and passsing to next page.
Gridview
<telerik:GridTemplateColumn FilterControlAltText="Filter TemplateColumn3 column" UniqueName="TemplateColumn3">
<ItemTemplate>
<asp:TextBox ID="txt_amnt" runat="server"></asp:TextBox> </td>
</ItemTemplate>
</telerik:GridTemplateColumn>
c# code
protected void chk_box_CheckedChanged(object sender, EventArgs e)
{
if (ViewState["dt"].ToString().Trim() != "NULL")
{
dt = (DataTable)ViewState["dt"];
}
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Amount");
}
CheckBox chk = (CheckBox)sender;
if (chk.Checked == true)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count-1 ]["Id"] = ((Label)chk.FindControl("lb_id")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Name"] = ((Label)chk.FindControl("lb_donation")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Amount"] = ((Label)chk.FindControl("lb_amount")).Text.Trim();
// dt.Rows[dt.Rows.Count + 1]["chkstatus"] = ((Label)chk.FindControl("lb_amount")).ToString().Trim();
}
else {
for (int i = 0; i < dt.Rows.Count; i++)
{
if(((Label)chk.FindControl("lb_id")).Text.Trim()==dt.Rows[i]["Id"].ToString().Trim())
{ dt.Rows.RemoveAt(i); }
}
}
ViewState["dt"] = dt;
double tamount = 0;
for (int i2 = 0; i2 < dt.Rows.Count; i2++)
{
tamount = tamount + Convert.ToDouble(dt.Rows[i2]["Amount"]);
}
lb_tamount.Text = tamount.ToString() ;
}
I believe your code for the CheckBox will always hit error.
How can you find a control inside a CheckBox ? Secondly your code is not complete as per the result you are showing. Anyway here is the idea how you can get checked item in your RadGrid.
First you need loop the RadGrid to get all checked CheckBox.
Then sum up the total and put it to the label.
This code just to mock up for your scenario. Please use TryParse to get the int value to ensure no converting error.
Code Behind
protected void chkCheck_CheckedChanged(object sender, EventArgs e)
{
// Variable
int total = 0;
int amt = 0;
int donateAmt = 0;
foreach (GridDataItem item in rg.Items)
{
// Find Control
CheckBox chkCheck = item.FindControl("chkCheck") as CheckBox;
Label lblAmount = item.FindControl("lblAmount") as Label;
TextBox txtAmount = item.FindControl("txtAmount") as TextBox;
// Reset Amount
amt = 0;
donateAmt = 0;
// Check
if (chkCheck != null && chkCheck.Checked)
{
// Check & Get Value
if (lblAmount != null && txtAmount != null)
{
// Check & Set
if (lblAmount.Text.Trim() != string.Empty)
amt = Convert.ToInt32(lblAmount.Text.Trim());
// Check & Set
if (txtAmount.Text != string.Empty)
donateAmt = Convert.ToInt32(txtAmount.Text.Trim());
// Check current Amount in stock and donate amt
if (donateAmt > amt)
{
donateAmt = amt;
txtAmount.Text = donateAmt + "";
}
// Reset to the text
}
total += donateAmt;
}
}
lblTotal.Text = total + "";
}
I have an issue when displaying bit fields in a GridView, when the GridView is rendered the bit field is blank.
Code to bind to my GridView:
protected void InitGridViewDisplay(GridView mygrid, Button mybutton, DataTable mydt, int i)
{
mygrid.DataSource = mydt;
mygrid.DataBind();
mygrid.Visible = true;
}
All other fields display correctly, but, the bit fields show as empty columns?
...after further discussion...
for (int j = 0; j < mydt.Columns.Count; j++)
{
string fieldtype = Convert.ToString(mydt.Columns[j].DataType);
if (fieldtype == "System.Boolean")
{
foreach (DataRow row in mydt.Rows)
{
string getrowvalue = Convert.ToString(row[j]);
switch (getrowvalue)
{
case "False":
{
row[j] = 0;
break;
}
case "True":
{
row[j] = 1;
break;
}
}
}
}
}
...Am I missing something? Columns is still blank when displayed in the GridView...
In my project I have a GridView with checkboxs. It checks and unchecks using a "Bit" value.
<Columns>
<ItemTemplate>
<asp:CheckBox id="chkStatus" Enabled='<%# Enable(Eval("Status")) %>' runat="server" />
</ItemTemplate>
At code behind
Protected Function Enable(ByVal sStatus As Boolean) As String
If UCase(Trim(sStatus)) = True Then
Return "true"
ElseIf UCase(Trim(sStatus)) = False Then
Return "false"
End If
End Function
Arun
I have a gridview with checkbox in my codebehind page. The functionality is that I need to select the records to be deleted using checkbox and click the delete button. I use the below code to do that.. But when I select the last row it does not get deleted. Instead it throws IndexOutOfRange/ System.FormatException ..
The error is thrown at this line
CheckBox chkb = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
for (int i = 0; i < count; i++)
{
CheckBox chkb = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
if (chkb.Checked == true)
{
string name = gvAll.Rows[i].Cells[3].Text;
if (!(name.Equals(System.DBNull.Value)))
{
a.delete(name);
}
}
}
It's an urgent issue. Please help..
How about a foreach?
foreach(GridViewRow row in gvAll.Rows)
{
CheckBox chkb = (CheckBox)row.Cells[0].FindControl("chk");
if (chkb.Checked == true)
{
string name = row.Cells[3].Text;
if (!(name.Equals(System.DBNull.Value)))
{
a.delete(name);
}
}
}
I have a DataList on ym web page, from which a user can choose a certain option within the DataList row.
I use the ItemCommand of DataList for this. Actually, I want to highlight the selected row when the user clicks on the item in the row.
<ItemTemplate>
<tr>
<td style="text-align:center"><asp:LinkButton ID="Item" Text='<%#Eval("Item")%>' CommandName="select" runat="server" /> <br /></td>
<td style="text-align:center"><asp:Label ID="lbQuery" Text='<%#Eval("Query")%>' runat="server" /><br /> </td>
</tr>
</ItemTemplate>
As shown above, the user can click on the LinkButton to choose an item. How do I highlight the corresponding row or only the cell?
Use following Method for Datalist to highlight selected row:
protected void DataList1_ItemDataBound(object sender,
DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
//Add eventhandlers for highlighting
//a DataListItem when the mouse hovers over it.
e.Item.Attributes.Add("onmouseover",
"this.oldClass = this.className;" +
" this.className = 'EntryLineHover'");
e.Item.Attributes.Add("onmouseout",
"this.className = this.oldClass;");
//Add eventhandler for simulating
//a click on the 'SelectButton'
e.Item.Attributes.Add("onclick",
this.Page.ClientScript.GetPostBackEventReference(
e.Item.Controls[1], string.Empty));
}
}
in your RowDataBound event add like this.
// Get the linklabel object and check for non nullity
LinkLabel lblItem = e.Item.FindControl("Item") as LinkLabel
if(lblitem !=null)
{
// add properties to it
lblItem.Attributes.Add("onclick", "this.style.background='#eeff00'");
}
on Item command
string[] str = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(str[2]); // ur item selected index
DataListItemCollection xx = DataList1.Items;
int count = 0;
foreach (DataListItem x in xx)
{
if (count == index)
{
(x.FindControl("Item") as LinkButton).BorderColor = System.Drawing.Color.Red;
(x.FindControl("Item") as LinkButton).BorderWidth = 1;
}
else
{
(x.FindControl("Item") as LinkButton).BorderColor = System.Drawing.Color.White;
(x.FindControl("Item") as LinkButton).BorderWidth = 0;
}
count = count + 1;
}
I have a Gridview
I have Click Button and two labels. (Risk_label and MV_label)
Risk and MV column has price value.
My Checkbox column names are NameCheckBoxField1 and NameCheckBoxField2
How can i calculate only "Which i selected in Gridview" Risk total and MV total in my labels?
Example;
Risk (Checked rows) --> 10, 20, 30 ---> Risk_label = 60
MV (Checked rows) --> 20, 30, 40 ---> MV_label = 90
EDİT: I try this code;
double sum = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField1");
if (cb.Checked)
{
double amount = Convert.ToDouble(gvr.Cells[1].Text);
sum += amount;
}
}
Risk_label.Text = sum.ToString();
But i getting an error.
protected void CalculateButton_Click(object sender, EventArgs e)
{
Int32 totalMVValue = 0, totalRiskValue = 0;
// Iterate through the Products.Rows property
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox mvSelectorCheckBox = (CheckBox)row.FindControl("MVSelector");
if (mvSelectorCheckBox != null && mvSelectorCheckBox.Checked)
{
// First, get the primaryId for the selected row
int mvValue=
Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
totalMVValue += mvValue;
}
CheckBox riskSelectorCheckBox = (CheckBox)row.FindControl("RiskSelector");
if (riskSelectorCheckBox != null && riskSelectorCheckBox.Checked)
{
// First, get the primaryId for the selected row
int riskValue =
Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
totalRiskValue += riskValue;
}
}
}
Looking at your last comment:
<asp:templatefield headertext=""> <itemtemplate> <asp:CheckBox DataField="NameCheckBoxField1" Checked="True" runat="server"></asp:CheckBox> </itemtemplate> </asp:templatefield>
Is DataField assigned NameCheckBoxField1? Or is it a typo?
It should be ID="NameCheckBoxField1"
I think jQuery would be the best option for you.
1. Add classes for Risk_Label and MV_Label
2. On checkbox click get the value of Risk_Label and MV_Label of the same row using the classes.
3. If it is checked then add value other wise subtract values.
$('.mygrid :checkbox').click(function () {
var amt = parseFloat($(this).parents('tr').find('.ClassRisk_label').text());
//One Fee Case
if (!isNaN(amt)) {
if ($(this).is(':checked')) {
totalAmt = totalAmt + amt;
}
else {
totalAmt = totalAmt - amt;
}
}
//Show the value...
});