Highlight the selected row in data list - c#

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;
}

Related

Gridview cannot parse input string is not correct

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>");
}

c# asp.net for append int value to the label id

I have the following label with ids:
<asp:Label ID="FromName0" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName1" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName2" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName3" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName4" runat="server" Visible="true"></asp:Label>
I want to assign the values to the label ids using for loop.
I am using the following tags in c#:
for (int i = 0; i < count; i++)
{
var label = this.Controls.Find("FromName " + i, true) as Label;
label.Text = Session["DeliverAddress" + i].ToString();
}
But ‘Find’ shows error like below:
System.Web.UI.ControlCollections does not have the definition for ‘Find’. But I have already added ‘System.Web.UI’ dll file. Can anyone help me?
I am using dotnet framework 4.0.
Thanks in Advance.
You can do this like this
public Control[] FlattenHierachy(Control root)
{
List<Control> list = new List<Control>();
list.Add(root);
if (root.HasControls())
{
foreach (Control control in root.Controls)
{
list.AddRange(FlattenHierachy(control));
}
}
return list.ToArray();
}
and
protected void Page_Load(object sender, EventArgs e)
{
Control[] allControls = FlattenHierachy(Page);
foreach (Control control in allControls)
{
Label lbl = control as Label;
if (lbl != null && lbl.ID == "FromName0")
{
lbl.ID = "myid";//Do your like stuff
}
}
}
Just use : Here MSDN article about FindControl
//
// Summary:
// Searches the page naming container for a server control with the specified identifier.
//
// Parameters:
// id:
// The identifier for the control to be found.
//
// Returns:
// The specified control, or null if the specified control does not exist.
public override Control FindControl(string id);
Here how your code should look like. Just as advice check if the control is null or the session variable is null, this can give you an exception.
for (int i = 0; i < count; i++)
{
var label = FindControl("FromName " + i) as Label;
if(label == null || Session["DeliverAddress" + i] == null)
continue;
label.Text = Session["DeliverAddress" + i].ToString();
}

Im trying to create an ASP.NET table using a for loop for a set of hyperlinks

I have list of hyperlinks which i want to use to create a 2x* table (* is number of hyperlinks)
Here is my code...
for (int rows = 0; rows < hlist.Count; rows++) //Create rows for the number of hyperlinks, so i will always have a spare row.
{
TableRow row = new TableRow(); // Create the new rows
table.Rows.Add(row); //Add rows to the table
for (int cells = 0; cells < 2; cells++)
{
TableCell cell = new TableCell();
for(int h = 0; h < hlist.Count; h++)
cell.Controls.Add(hlist[h]);
row.Cells.Add(cell);
}
}
All this does is list all my hyperlinks in a single column table, with a new row for each hyperlink!
Any help would be appreciated!!
Thanks
Assuming that you want to create a table that shows two hyperlinks per row, you could try the following code:
for (int i = 0; i < hlist.Count; i += 2)
{
TableRow row = new TableRow(); // Create the new rows
table.Rows.Add(row);
for (int j = i; j < Math.Min(i + 2, hlist.Count); j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(hlist[j]);
row.Controls.Add(cell);
}
}
However, using dynamically added controls in ASP.NET is complex if you want them to react on events. So I'd propose to check whether you could change your approach so that you can use a Repeater instead. In order to do so, you'd first have to change your data model, e.g. to a list of Pair objects that contain two URLs, e.g.:
public void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
IEnumerable<Uri> uris = GetUris();
List<Tuple<Uri, Uri>> pairs = new List<Tuple<Uri, Uri>>();
for (int i = 0; i < uris.Count; i += 2)
{
var uri1 = uris[i];
var uri2 = i + 1 < uris.Count ? uris[i + 1] : null;
pairs.Add(new Tuple<Uri, Uri>(uri1, uri2));
}
rpt.DataSource = pairs;
rpt.DataBind();
}
}
If your URLs are not compatible with a Uri (maybe they contain a leading ~), you can also use strings instead of Uri.
The markup for your the Repeater would look similar to this:
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HyperLink runat="server" Text="Link 1"
NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "Item1") %>' />
</td>
<td>
<asp:HyperLink runat="server" Text="Link 1"
NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "Item2") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

How to make a customized GridView that is completely user defined

I have a GridView:
On Button_Click
I want the first column of my GridView with the items of ListBox1 and 2nd column with the EDIT link and from 3rd column on wards I want the headers as the items of ListBox2.
So far I am able to achieve EDIT link in the 2nd column and from 3rd column on wards the headers of the GridView with ListBox2 items.
Now I want ListBox1 items as the first column of my GridView. I have attached an image with show what exactly I want and what I have achieved so far.
Kindly help me on. Thank you.
The .cs code I have designed is:
DataTable dt = new DataTable();
DataRow rw = default(DataRow);
for (int i = 0; i < ListBox3.Items.Count; i++)
{ dt.Columns.Add(ListBox3.Items[i].ToString(),System.Type.GetType("System.String"));
}
for (int j = 0; j < count; j++)
{
rw = dt.NewRow();
for (int i = 0; i < ListBox3.Items.Count; i++)
{
rw[ListBox3.Items[i].ToString()] = " ";
}
dt.Rows.Add(rw);
}
GridView2.DataSource = dt;
GridView2.DataBind();
The asp code for GridView is :
<Columns>
<asp:TemplateField HeaderText="Locations">
<ItemTemplate>
<asp:Label ID="Lab1" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
First create a event of your gridview_RowDataBound
and change value of your label
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl1= ((Label)e.Row.FindControl("Lab1"));
lbl1.text = ListBox1.items[e.Row.RowIndex].ToString();
}
}

Total of Selected Items in Gridview

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...
});

Categories

Resources