How to multiply the different selected checkboxes text into textbox? - asp.net

If i have 55 checkboxes with different text 1,2,3,4 and so on ....and a textbox where it display how many no. of checkboxes checked ..... i want to multiply the multiple selected checkbox text with how many checkboxes are checked in other textbox .....
i want to do this using vb.net, asp.net

Like cdhowie i'm a little confused with your question, but if I understand well it's seems pretty simple.
You must put (eventually dynamically generated, it's the same) all you checkboxes in a container like a placeholder, and in your code behind to loop through them and test which of them or checked. If one is, you take the associated text, convert it in int, and add it to your total.
Here is a very little sample in c# :
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="ph" runat="server">
<asp:CheckBox ID="cb" runat="server" Text="3"/> <asp:CheckBox ID="CheckBox1" runat="server" Text="3"/> <asp:CheckBox ID="CheckBox2" runat="server" Text="3"/> <asp:CheckBox ID="CheckBox3" runat="server" Text="3"/> <asp:CheckBox ID="CheckBox4" runat="server" Text="3"/> <asp:CheckBox ID="CheckBox5" runat="server" Text="3"/>
</asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
protected void Button1_Click(object sender, EventArgs e)
{
int n = 0;
foreach (Control ctl in ph.Controls)
{
CheckBox cb = ctl as CheckBox;
if (cb != null && cb.Checked)
{
n += Convert.ToInt32(cb.Text);
}
}
Response.Write(n);
}
Of course, there is many other ways to do that, but this is one is easy to understand like you seem to be a beginner.

Related

Get value of TextBox in Panel in <table> in TemplateField in GridView

I have a GridView with a TemplateField. Inside the ItemTemplate there are 2 TextBox's and then a <table> with an Panel. In that Panel there's another TextBox.
How do I get the value of that last TextBox?
I have the index of the gridview's row, but I don't know how to get on from there.
(Data from DB is bound at page load).
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:GridView ID="grv_Four_Rows" runat="server" AutoGenerateColumns="False"
ShowHeader="False" CellPadding="3" CssClass="myGrid" DataKeyNames="Test1_First_Name">
<RowStyle BackColor="#b5c7de" />
<AlternatingRowStyle BackColor="#d1e0e0" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txbFirstName" runat="server" CssClass="myTextBox" ReadOnly="false" Text='<%# Eval("Test1_First_Name")%>'></asp:TextBox>
<asp:TextBox ID="txbLastName" runat="server" CssClass="myTextBox" ReadOnly="true" Text='<%# Eval("Test1_Last_Name")%>'></asp:TextBox>
<table style="width: 350px;">
<asp:Panel ID="upp_2nd_row" runat="server" Visible="true">
<td style="float: left">
<a style="color: red; font-weight: bold;">Address: </a>
<asp:TextBox ID="txbAddress" Width="200px" Font-Bold="true" runat="server" Text='<%# Eval("Test1_Address")%>' />
</td>
<td style="float: right">
<asp:Button ID="btn_Edit_Details" runat="server" Text="Go" Font-Bold="true"
OnClick="my_Update_details" CommandArgument='<%#DataBinder.Eval(Container, "DataItemIndex")%>' />
</td>
</asp:Panel>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Label ID="lblMessage1" runat="server" BackColor="Yellow" Font-Bold="true"></asp:Label>
C# Code behind:
protected void my_Update_details(object sender, EventArgs e)
{
string my_row_index = (sender as Button).CommandArgument;
lblMessage1.Text = "Row Index: " + my_row_index;
}
When I click the "Go" button in any row, the my_Update_details event is fired. All it does is, it displays the gridview's current row's index, and the value is correct.
But in the my_Update_details I also want to pick the values of the textbox's, and that's where I'm stuck (user is supposed to change their values and the 'Go' button should update the DB). In the following example I clicked the button in the 4th row and it correctly displays the index as 3 :
So this is how it works: first I rack my brains for a couple of days, then I post a question in SO, then - after 2 minutes I find a solution...
All I did was add a line in the my_Update_details method (the second line) :
protected void my_Update_details(object sender, EventArgs e)
{
string my_row_index = (sender as Button).CommandArgument;
TextBox AAAAAA = (TextBox)grv_Four_Rows.Rows[Convert.ToInt32(my_row_index)].Cells[0].FindControl("txbAddress");
lblMessage1.Text = "Address: " + AAAAAA.Text;
lblMessage2.Text = "Row Index: " + my_row_index;
}
and now I get:
which is exctly what I needed : to get the value that's in the txbAddress textbox.
Hope it will help someone in the future....

Find which input radio button is checked in code behind

I have the following ListView that contains Input radio buttons:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
<ItemTemplate>
<input id="Radio1" name="BG_name" type="radio" value="<%# Eval("BG_fileName") % >"/>
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("BG_fileName") %>' />
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource_BGlist" runat="server" ConnectionString="Data Source=tcp:cg26trmnla.database.windows.net,1433;Initial Catalog=cookniche;Integrated Security=False;User ID=PublicSQLcookniche#cg26trmnla;Password=Abounakhle80+;Connect Timeout=30;Encrypt=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [BG_fileName] FROM [BackgroundImages]"></asp:SqlDataSource>
I want to check which radio button is checked from code behind. I'm using the following code but it's obviously not correct.
foreach (ListViewItem itemRow in this.ListView1.Items)
{
RadioButton radioBtn = new RadioButton();
radioBtn = (RadioButton)itemRow.FindControl("Radio1");
if (radioBtn.Checked)
{
//do stuff
}
}
You are doing almost right. Only few minor things needs to be changed in your code.
Add runat="Server" in your radio button. Because if it will not runat="server" then you will not find radiobutton at code behind. have a look at below HTML code:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
<ItemTemplate>
<input id="Radio1" runat="server" name="BG_name" type="radio" value="<%# Eval("BG_fileName") %>"/>
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("BG_fileName") %>' />
</ItemTemplate>
</asp:ListView>
And in your code behind you are casting to RadioButton this RadioButton indicates server side control of radio button. Instead of that you should use HtmlInputRadioButton as shown below:
foreach (ListViewItem itemRow in this.ListView1.Items)
{
var radioBtn = (HtmlInputRadioButton)itemRow.FindControl("Radio1");
if (radioBtn.Checked)
{
// Do Stuff
}
}
To Apply Grouping with RadioButton
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<input runat="server" name="BG_name" type="radio" ID="radio1" value='<%# Eval("Id") %>' ClientIDMode="Static" class="radioBGName" />
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("Title") %>' />
</ItemTemplate>
</asp:ListView>
<script type="text/javascript">
$('.radioBGName').click(function () {
var controlId = $(this).attr('name');
$('.radioBGName').each(function () {
if (controlId != $(this).attr('name')) {
$(this).removeAttr('checked');
}
});
});
</script>
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
RadioButton c1 = (RadioButton)e.Item.FindControl("Radio1");
if (radioBtn.Checked)
{
//do stuff
}
}
}
UPDATE
in Page_Load you need to know the row index and retrieve the control like this
RadioButton radio= this.ListView1.Items[<row_index>].FindControl("Radio1") as RadioButton

how to use radio buttons in grid view in asp.net

How do I implement radio buttons in a grid view? I used asp:radiob button but the problem is that it selects all the radio buttons in the list. How do I select only one radio button at a time?
You can add the radio buttons in GridView using TemplateField.
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rdoYes" runat="server" Text="Yes" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
You can select individual radio button if you added in GridView like above.
Make all the radio buttons part of a group by defing a GroupName for them.
Here is an example:
<html>
<body>
<form runat="server">
Select your favorite color:
<br />
<asp:RadioButton id="red" Text="Red" Checked="True"
GroupName="colors" runat="server"/>
<br />
<asp:RadioButton id="green" Text="Green"
GroupName="colors" runat="server"/>
<br />
<asp:RadioButton id="blue" Text="Blue"
GroupName="colors" runat="server"/>
<br />
<asp:Button text="Submit" OnClick="submit" runat="server"/>
<p><asp:Label id="Label1" runat="server"/></p>
</form>
</body>
</html>
If your going to use a grid view and u want to put a radio button on a TemplateField to act as a pointer to your selection just use this code on the rbSelector_CheckedChanged()...
protected void rbSelector_CheckedChanged(object sender, System.EventArgs e)
{
//Clear the existing selected row
foreach (GridViewRow oldrow in GridView1.Rows)
{
((RadioButton)oldrow.FindControl("rbSelector")).Checked = false;
}
//Set the new selected row
RadioButton rb = (RadioButton)sender;
GridViewRow row = (GridViewRow)rb.NamingContainer;
((RadioButton)row.FindControl("rbSelector")).Checked = true;
}
If theres any problem just let me know, ok? hope this code can help newbies out there like me.
Amit Patel
Use a TemplateField with a standard HTML control then on the codebehind use Request.Form.
ASPX:
<asp:TemplateField>
<ItemTemplate>
<input type="radio" name="group1" value='<%# Eval("YourValue") %>' />
</ItemTemplate>
</asp:TemplateField>
Codebehind:
string radioValue = Request.Form["group1"].ToString();

How to use DataBinding to set the ID of asp:CheckBox controls

I have some ASP that I want to look kinda of like this:
<asp:DataGrid ID="dgEnum" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="<%# some big DataBinder expression %>" runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
but that gives me a:
Parser Error Message: The ID property of a control can only be set using the ID attribute in the tag and a simple value. Example: <asp:Button runat="server" id="Button1" />
Anyone have an idea how to hack around that?
Anyone have an idea how to hack around that?
You can't, and you don't. You can store the required data somewhere besides the ID. At the very least, a sibling HiddenField could be used.
<script runat="server">
void Checkbox_CheckedChanged(object sender, EventArgs e) {
var c = (Checkbox)sender;
if (!c.Checked) {
return;
}
var hfv = (HiddenField)c.Parent.FindControl("hfvMyData");
var myData = hfv.Value;
/* Do something with myData */
}
</script>
<asp:DataGrid ID="dgEnum" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox runat="server" OnCheckedChanged="Checkbox_CheckedChanged" />
<asp:HiddenField id="hfvMyData" runat="server" Value='<%# Eval("MyData") %>' />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Other options could be DataKeys, a server side (perhaps cached or Session data) indexed list, or a ViewState indexed list.
If you really wanted to bastardize WebForms, you can put your data into CssClass...but that's just crazy. ;)
Not sure what you are intending to do here, but you can just go straight to the html controls ie <input type="checkbox" id="<%# some expresssion %>" />
Or you don't do this and query for it on the server side. I.e. find the row you want and then use FindControls() to get the checkbox for that row.

How do you bind a DropDownList in a GridView in the EditItemTemplate Field?

Here's my code in a gridview that is bound at runtime:
...
<asp:templatefield>
<edititemtemplate>
<asp:dropdownlist runat="server" id="ddgvOpp" />
</edititemtemplate>
<itemtemplate>
<%# Eval("opponent.name") %>
</itemtemplate>
</asp:templatefield>
...
I want to bind the dropdownlist "ddgvOpp" but i don't know how. I should, but I don't. Here's what I have, but I keep getting an "Object reference" error, which makes sense:
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //skip header row
{
DropDownList ddOpp = (DropDownList)e.Row.Cells[5].FindControl("ddgvOpp");
BindOpponentDD(ddOpp);
}
}
Where BindOpponentDD() is just where the DropDownList gets populated. Am I not doing this in the right event? If not, which do I need to put it in?
Thanks so much in advance...
Ok, I guess I'm just dumb. I figured it out.
In the RowDataBound event, simply add the following conditional:
if (myGridView.EditIndex == e.Row.RowIndex)
{
//do work
}
Thanks to Saurabh Tripathi,
The solution you provided worked for me.
In gridView_RowDataBound() event use.
if(gridView.EditIndex == e.Row.RowIndex && e.Row.RowType == DataControlRowType.DataRow)
{
// FindControl
// And populate it
}
If anyone is stuck with the same issue, then try this out.
Cheers.
I had the same issue, but this fix (Jason's, which is adding the conditional to the handler) didn't work for me; the Edit row never was databound, so that condition never evaluated to true. RowDataBound was simply never called with the same RowIndex as the GridView.EditIndex. My setup is a little different, though, in that instead of binding the dropdown programmatically I have it bound to an ObjectDataSource on the page. The dropdown still has to be bound separately per row, though, because its possible values depend on other information in the row. So the ObjectDataSource has a SessionParameter, and I make sure to set the appropriate session variable when needed for binding.
<asp:ObjectDataSource ID="objInfo" runat="server" SelectMethod="GetData" TypeName="MyTypeName">
<SelectParameters>
<asp:SessionParameter Name="MyID" SessionField="MID" Type="Int32" />
</SelectParameters>
And the dropdown in the relevant row:
<asp:TemplateField HeaderText="My Info" SortExpression="MyInfo">
<EditItemTemplate>
<asp:DropDownList ID="ddlEditMyInfo" runat="server" DataSourceID="objInfo" DataTextField="MyInfo" DataValueField="MyInfoID" SelectedValue='<%#Bind("ID") %>' />
</EditItemTemplate>
<ItemTemplate>
<span><%#Eval("MyInfo") %></span>
</ItemTemplate>
</asp:TemplateField>
What I ended up doing was not using a CommandField in the GridView to generate my edit, delete, update and cancel buttons; I did it on my own with a TemplateField, and by setting the CommandNames appropriately, I was able to trigger the built-in edit/delete/update/cancel actions on the GridView. For the Edit button, I made the CommandArgument the information I needed to bind the dropdown, instead of the row's PK like it would usually be. This luckily did not prevent the GridView from editing the appropriate row.
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ibtnDelete" runat="server" ImageUrl="~/images/delete.gif" AlternateText="Delete" CommandArgument='<%#Eval("UniqueID") %>' CommandName="Delete" />
<asp:ImageButton ID="ibtnEdit" runat="server" ImageUrl="~/images/edit.gif" AlternateText="Edit" CommandArgument='<%#Eval("MyID") %>' CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="ibtnUpdate" runat="server" ImageUrl="~/images/update.gif" AlternateText="Update" CommandArgument='<%#Eval("UniqueID") %>' CommandName="Update" />
<asp:ImageButton ID="ibtnCancel" runat="server" ImageUrl="~/images/cancel.gif" AlternateText="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
And in the RowCommand handler:
void grdOverrides_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
Session["MID"] = Int32.Parse(e.CommandArgument.ToString());
}
The RowCommand, of course, happens before the row goes into edit mode and thus before the dropdown databinds. So everything works. It's a little bit of a hack, but I'd spent enough time trying to figure out why the edit row wasn't being databound already.
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (grdDevelopment.EditIndex == e.Row.RowIndex && e.Row.RowType==DataControlRowType.DataRow)
{
DropDownList drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
}
}
Try this one
This will help u
This code will be do what you want:
<asp:TemplateField HeaderText="garantia" SortExpression="garantia">
<EditItemTemplate>
<asp:DropDownList ID="ddgvOpp" runat="server" SelectedValue='<%# Bind("opponent.name") %>'>
<asp:ListItem Text="Si" Value="True"></asp:ListItem>
<asp:ListItem Text="No" Value="False"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("opponent.name") %>'></asp:Label>
</ItemTemplate>

Resources