Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cant get color set in HTML Javascript 1

Status
Not open for further replies.

ISPrincess

Programmer
Feb 22, 2002
318
0
0
US
I have posted this in asp.net forum also, but since it involves Java, I wanted to put it here also.

In Server VB:
Code:
If dgMoves.Items(i).BackColor.Equals(System.Drawing.Color.LightSteelBlue) Then
                SetAlertMessage("Selected: " & i)
      End If

never equates to TRUE.


In server VB code, I keep getting color.empty returned event though I have set it in HTML

In my HTML I have Javascript . (I had to use the #b0c4de and not the color name because the javascript wasnt behaving)


Code:
SRow.style.backgroundColor = ( bg == '#b0c4de' ) ? '#ffffff' : '#b0c4de';

Also, dgMoves.Items(i).BackColor.ToString returns Color.Empty.

I think I amm missing something very obvious (as usual), please, can anyone see what is wrong here?

PH
I was walking home one night and a guy hammering on a roof called me a paranoid little weirdo.
In morse code.
-Emo Phillips
 
It gets very confusing when you mix up language names: are you using VB, VB.NET, Java, and JavaScript?

I would guess you are using VB.NET and JavaScript. The "JavaScript" you posted isn't JavaScript, it's a CSS style declaration, and as such can't contain JavaScript. I don't think you can use the teriary operator within CSS.

What is the "dbMoves" control? What is "SRow"?

Or, perhaps I'm just misreading your entire post. Can you give us some more detail?

Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
Very sorry about all that. I am confused as I am sure you can see.

Here is the Javascript to highlight a row in Datagrid:

Code:
function HighlightRow(SRow)    
{  //Begin Function
	var bg = SRow.style.backgroundColor;
	SRow.style.backgroundColor = ( bg == '#b0c4de' ) ? '#ffffff' : '#b0c4de';
}

In the VB.net code during the Row_DataBoudn event I have added onclick event to call HighlightRow:

Code:
e.Item.Attributes.Add("OnClick", "HighlightRow( this );")

When the user clicks button "Process" I would like VB.Net code to run through each item in the grid and perform some action if the row is highlighted.

Does this clarify?



PH
I was walking home one night and a guy hammering on a roof called me a paranoid little weirdo.
In morse code.
-Emo Phillips
 
Your problem is that the bg does not contain what you might think it does. Try putting an alert(bg) in your HighlightRow function and you'll see that it will equal neither '#b0c4de' nor '#ffffff'. Instead of using .style you have to use .currentstyle. This should work:
Code:
function HighlightRow(SRow)    
{  //Begin Function
    var bg = SRow.currentStyle["backgroundColor"];
    SRow.style.backgroundColor = ( bg == '#b0c4de' ) ? '#ffffff' : '#b0c4de';
}

-kaht

banghead.gif
 
The javascript works fine, but I cannot get VB.net code to be able to access or do not know what property of the datagrid's row to access in order to find out if the backgroundcolor or backcolor has been set to LightSteelBlue.

If I were to change this javascript to set .CurrentStyle instead of .style then what property of the datagrid.item could I use to check the .currentstyle.backgroundcolor??

PH
I was walking home one night and a guy hammering on a roof called me a paranoid little weirdo.
In morse code.
-Emo Phillips
 
style.backgroundColor" is a JavaScript property. "BackColor" is an ASP.NET Server Control property. They don't equate.

Either set your background color in JavaScript or VB.NET. Then perform your check in the same language. In other words, do it all client-side in JavaScript, or do it all server-side in VB.NET.



Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
I had the highlighting all done server side before but due to postbacks I need to make the highlighting client side.

Do you know of anything at all that I can set client side that I can equate back to the VB.Net server side?

ie:
Can I change the text of a cell in the grid using Javascript? Just an idea. If so, could you provide me a sample of how that could be done?

PH
I was walking home one night and a guy hammering on a roof called me a paranoid little weirdo.
In morse code.
-Emo Phillips
 
Passing "client stuff" to the server: what I usually do is have my JavaScript function set a hidden form variable. Then, in my Page_Load handler, I check the value of the hidden variable.

To change the "text" of a cell can be tricky, because of the relationship of table elements to each other in the DOM. Do you give each <td> a unique ID? And which doctype are you using? Does it have to be cross-browser?





Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
Changing td contents:

Code:
<html>
<body>
<table>
<tr>
  <td onmouseover="this.innerHTML='cell 1';">CELL ONE.</td>
  <td onmouseover="this.innerHTML='cell 2';">CELL TWO.</td>
</tr>
</table>
</body>
</html>

This is easy because the td is referring directly to itself with "this".

With a JavaScript function, you have to pass in the keyword "this", if the td has an event handler.

If the td itself isn't calling the function, your function will have to FIND the td, which you can only really do if you assign an ID to each td.



Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
Wow. If it isnt obvious by now, I am self-taught and my teacher is aweful ;) - So I will TRY to answer what you have asked.

The datagrid is a the asp.net datagrid control. I just found out a few days ago that it renders itself as <TABLE><TR> etc in the HTML. So I cannot answer
Do you give each <td> a unique ID?

Not sure what you mean by doctype, but this application will only be used by ie browsers.

I have and am setting hidden form inputs in other cases, but do not see how I can do this for a datagrid that can have any number of rows displayed / selected.

PH
I was walking home one night and a guy hammering on a roof called me a paranoid little weirdo.
In morse code.
-Emo Phillips
 
In your DataGrid, you have Templates, correct? If you set an ID in your template, then each server control in the template will get an ID. ASP.NET will "create" a unique ID, by taking the ID from the template and adding a number to it.

I'll code up a little example for you, if that would help.

A "Doctype" is a declaration you make at the top of the webpage, even before the <HTML> tag, that informs the browser what "flavor" of HTML and/or XHTML you are serving.



Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
In your DataGrid, you have Templates, correct? If you set an ID in your template, then each server control in the template will get an ID. ASP.NET will "create" a unique ID, by taking the ID from the template and adding a number to it.

I'll code up a little example for you, if that would help.

A "Doctype" is a declaration you make at the top of the webpage, even before the <HTML> tag, that informs the browser what "flavor" of HTML and/or XHTML you are serving.

As for a hidden variable, you could simply have a single hidden element, and set it equal to the id of the relevant TD.



Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
I cannot change the table contents because at design time it is a datagrid. At run time it becomes a table.

I do see what you are saying though it makes sense. Can you help me just alittle more?

1. Could I do what you suggest in an attribute added in the VB.net code? similar to:
e.Item.Attributes.Add("OnClick", "HighlightRow( this );")

2. In the above Onclick event I would need it to do 2 things - I am not sure how to do that. I would need it to perform the highlightrow as shown above AND I would need it change come text as you suggested.

3. I do also need a mouse over event to highlight AND Change text as you suggest but ONLY IF the hidden field txtIsMouseDown.value = 1. In other words, ONLY if the user is Mousing Over :) while holding the left click down. How would I write that?

4. I am not sure how the datagrid renders the cells as <TD> but say i wanted the datagrid.item(0).cells(5).text to change to '1' during the above event(s), how would I write that?

I am sorry to ask so many questions, but I am really getting desperate with this. I have asked for our company to buy a third party datagrid tool, but was denied.

I also want to tell you how much i appreciate your help. Thanks.


PH
I was walking home one night and a guy hammering on a roof called me a paranoid little weirdo.
In morse code.
-Emo Phillips
 
tgreer said:
I'll code up a little example for you, if that would help.

Yes, please!!! Thank you !@

PH
I was walking home one night and a guy hammering on a roof called me a paranoid little weirdo.
In morse code.
-Emo Phillips
 
Sorry about the double-post. Here's a link to a sample application. It isn't exactly what you need, but it was already written and does show how to use JavaScript in conjunction with a datagrid:


If you fill in a quantity, then click that row's button, a JavaScript alert will show you the quanity that you entered in that row.

The HTML/WebForm1 code:

Code:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="DataGrid_JS.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
	<HEAD>
		<title>WebForm1</title>
		<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
		<meta name="CODE_LANGUAGE" Content="C#">
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" content="[URL unfurl="true"]http://schemas.microsoft.com/intellisense/ie5">[/URL]
		<script>
	function showQuantity(x)
	{
		var btnID = x.id;
		var btnName = "cmdAddToShip";
		var txtName = "txtQuanShipped";
		
		var startPos = btnID.indexOf(btnName,0);
		
		var txtID = btnID.substring(0,startPos) + txtName + btnID.substring(startPos+btnName.length,btnID.length);
		
		alert(document.getElementById(txtID).value);
		
	}
		</script>
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
			<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px" runat="server"
				OnDataBinding="countCols">
				<Columns>
					<asp:TemplateColumn HeaderText="Amount Shipped">
						<ItemTemplate>
							<ASP:TEXTBOX id="txtQuanShipped" runat="server" width="42px"></ASP:TEXTBOX>
						</ItemTemplate>
					</asp:TemplateColumn>
					<asp:TemplateColumn>
						<ItemTemplate>
							<ASP:BUTTON runat="server" id="cmdAddToShip" text="Add To Shipment" commandname="AddToShip"
								causesvalidation="false"></ASP:BUTTON>
						</ItemTemplate>
					</asp:TemplateColumn>
				</Columns>
			</asp:DataGrid>
		</form>
	</body>
</HTML>

Notice that in my templates, I give the textbox and the button, an ID. ASP.NET will build a unique ID for each control from that template ID.

The code-behind (sorry, I code C#):

Code:
		private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			Button cmdAdd = new Button();
			if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
			{
				cmdAdd = (Button) e.Item.Cells[1].FindControl("cmdAddToShip");
				cmdAdd.Attributes.Add("onclick", "return showQuantity(this);");
			}
		}

That is to bind a client-side onclick event to the button. When the button is clicked, the JavaScript "showQuantity" function will run.

That script determines the actualy run-time ID of the element that was clicked.

When you run the app and look at the rendered HTML (View Source), you see that controls in the templae with ID set to

"txtQuanShipped"

get rendered as:

id="DataGrid1__ctl1_txtQuanShipped"
id="DataGrid1__ctl2_txtQuanShipped"
id="DataGrid1__ctl3_txtQuanShipped"

I know it's complex, but to summarize:

1) You can dynamically assign an ID to every rendered control, by assigning a "seed" ID in your template.

2) You can dynamically wire a JavaScript function to rendered controls by using the DataGrid "ItemDataBound" event. In that code, you use the keyword "this" to pass the ID of the control to the JavaScript function.

Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
NOTE: In the above, I'm not dealing with the "naked" TD elements. Instead, I'm putting ASP.NET Server Controls into my DataGrid template. I'm manipulating THOSE, by their ID, in a JavaScript function.

Your JavaScript function can make multiple changes to a single element. Change the color, the innnerHTML, even assign or de-assign event handlers so that things only happen ONCE, or only happen IF the "first thing" already happened.

You could use an onclick event, for example, to assign an onmouseover event... so that AFTER something has been clicked, moving the mouse over it does something.



Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
I am working on it now.

I am not sure exactly what this line is doing:
Code:
 var txtID = btnID.substring(0,startPos) + txtName + btnID.substring(startPos+btnName.length,btnID.length);

I do not have a button (cmdAddToShip) for user to click on. My onclick event is for the row assigned in the item_databound (or row_databound):
Code:
e.Item.Attributes.Add("OnClick", "HighlightRow( this );")

So I do not know how to assign anything to btnName.

I am sorry, I am probably missing your point and I do not want to take more of your time, but if you have it (time), again, I would greatly appreciate it.

PH
I was walking home one night and a guy hammering on a roof called me a paranoid little weirdo.
In morse code.
-Emo Phillips
 
The first line of code determines the ID of the textbox based upon the ID of the button that was clicked.

You don't have to have buttons. In your HighlightRow function, you pass in "this", which is the current object.

So if your function signature looks like: HighlightRow(x), "x" will be the "row". "x.id" will be the id of that row.

document.getElementById(x.id) would return that row. You can then change it's .innerHTML and .backgroundColor properties.

If you want more specific help, you'll have to show me some code. Post the HTML view of your DataGrid/WebForm.

And we're way off-topic here. You can email me if you like, my email address is on my website.



Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
I guess the topic name s/b something like Perpetuating Client Side Datagrid Row selections back to Server. But I did not know I would not be able to capture the Rows.backcolor on the server. This is how this whole nightmare started.

Per your request I posting simple HTML and vb code-behind:
Code:
<HTML>
<HEAD>
<title>TestMultiSelect</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="[URL unfurl="true"]http://schemas.microsoft.com/intellisense/ie5">[/URL]
<SCRIPT language="javascript">
function HighlightRow(SRow)    
{  //Begin Function
var bg = SRow.style.backgroundColor;
SRow.style.backgroundColor = ( bg == '#b0c4de' ) ? '#ffffff' : '#b0c4de';
//Change value of isSelected text
//SRow is Datagrid Row
	var btnID = SRow.id;
	var txtName = "isSelected";
	var startPos = btnID.indexOf(btnName, 0);
	var txtID = btnID.substring(0, startPos) + txtName + btnID.substring(startPos+txtName.length,btnID.length);
	//alert(btnID);
//set txt field in grid to 1
document.getElementById(txtID).value = "1"	} //End Function
// -->
</SCRIPT>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:datagrid id="datagrid1" runat="server" EnableViewState="true" AllowSorting="True" AutoGenerateColumns="false"
OnItemDataBound="datagrid1_RowDataBound" height="50%">
	<Columns>
	<asp:BoundColumn HeaderText="Printer #" DataField="DeviceNo" />
	<asp:TemplateColumn HeaderText="IsSelected">
		<ItemTemplate>
		<asp:TextBox ID="isSelected" Runat="server" />
		</ItemTemplate>
        </asp:TemplateColumn>
</Columns>
</asp:datagrid>
<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 312px; POSITION: absolute; TOP: 16px" runat="server"
Text="Button"></asp:Button>
</form>
</body>
</HTML>

VB.net Code behind to assign onclick attributes to Row:
Code:
Sub datagrid1_RowDataBound(ByVal Sender As Object, ByVal e As DataGridItemEventArgs)
        If e.Item.ItemType <> ListItemType.Header And _
            e.Item.ItemType <> ListItemType.Footer Then

            'Client side Javascript that 
            '   1. Highlights row
            '   2. Changes isSelected Text field in grid
            e.Item.Attributes.Add("OnClick", "HighlightRow( this );")
        End If

    End Sub

I have also put a button on the form to represent "Process or Submit". Here is the onclick event of that which at this time, simply gathers all the selected item's itemindexes and displays them:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim strSelected As String
        Dim i As Integer
        Dim txtSelect As TextBox
        For i = 0 To datagrid1.Items.Count - 1
            txtSelect = datagrid1.Items(i).FindControl("isSelected")

            'item is marked selected
            If txtSelect.Text = "1" Then
                strSelected = strSelected & datagrid1.Items(i).ItemIndex & "; "
            End If
        Next
        SetAlertMessage(strSelected)
    End Sub
End Class

PH
I was walking home one night and a guy hammering on a roof called me a paranoid little weirdo.
In morse code.
-Emo Phillips
 
Ok, here is the link to an ASP.NET application which will:

1) Change the background color of an entire row, when that row is clicked, and

2) Changes the content of a cell (<td> element) in that row.


The only thing I did differently, is that I had to create a DataTable, DataColumn, and DataRow objects to bind to the DataGrid. I converted VB.NET to C#. I made the OnItemDataBound event assignment with a delegate rather than an inline attribute.

But the relevant code is JavaScript:

Code:
function HighlightRow(SRow)    
{
  var bg = SRow.style.backgroundColor;
  SRow.cells[0].innerHTML = SRow.cells[0].innerHTML + "_sel";
  SRow.style.backgroundColor = ( bg == '#b0c4de' ) ? '#ffffff' : '#b0c4de';
}

Each time the row is clicked, the text "_sel" is appended to the contents of the first cell.

The "trick" to understanding this, is that your table row contains a "cells" collection, zero indexed.

So the first <td> of your <tr> is "SRow.cells[0]", the second <td> is "SRow.cells[1]", and so on. You can change the contents of the cell via its ".innerHTML" property.

You should note this only works in IE. FireFox doesn't support changing colors in this manner.

This way you change the background color of a row, and the contents of that row's cells, all in JavaScript, without recourse to a PostBack or server-side code.

My standard plug: if this post helped you, please support Tek-Tips by visiting some of their sponsors. My site is also supported by advertising, if you'd like to thank me personally.

Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top