Solved

Add onclick attribute to CheckBoxList inside another control

Posted on 2009-07-11
10
1,470 Views
Last Modified: 2012-05-07
Look, In my aspx page I have a DIV like this with the Style propertie setup in "none":

HTML:
            <div id="LstBoxContainer" style="display: none; ">
                    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetCountries"
                        TypeName="TemplateData"></asp:ObjectDataSource>
                    <asp:CheckBoxList ID="CheckBoxList1" runat="server" CssClass="ob_gEC" DataTextField="CountryName" DataValueField="CountryID" Width="100%" DataSourceID="ObjectDataSource1">
                    </asp:CheckBoxList>

.NET CodeBehind:
        CheckBoxList1.Attributes.Add("onclick", "SetValue(this)");

I need to move the <div id="LstBoxContainer....etc,etc </div> inside a custom aspx control called OboutGrid.
To do this I add the next code after "CheckBoxList1.Attributes.Add("onclick...etc,etc":

 CheckBoxList CheckBoxList1 = (CheckBoxList)grid1.Templates[0].Container.FindControl("CheckBoxList1");

But tha page crash with a NullReferenceException

Any help? I think the problem is in FindControl function
<%@ Page Language="C#"%>
<%@ Register TagPrefix="obout" Namespace="Obout.Grid" Assembly="obout_Grid_NET" %>
<%@ Register TagPrefix="obout" Namespace="Obout.Interface" Assembly="obout_Interface" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Register TagPrefix="obout" Namespace="OboutInc.Combobox" Assembly="obout_Combobox_Net" %>
 
<script language="C#" runat="server">
	void Page_load(object sender, EventArgs e)		
	{		
		if (!Page.IsPostBack)
		{
			CreateGrid();
            Combobox cbo1 = (Combobox)grid1.Templates[0].Container.FindControl("cbo1");
            
		}
        CheckBoxList1.Attributes.Add("onclick", "SetValue(this)");
	}
	
	void CreateGrid()
	{
		OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../App_Data/Northwind.mdb"));
 
		OleDbCommand myComm = new OleDbCommand("SELECT * FROM Suppliers", myConn);
		myConn.Open();		
		OleDbDataReader myReader = myComm.ExecuteReader();
 
		grid1.DataSource = myReader;
		grid1.DataBind();
 
		myConn.Close();	
	}	
		
	void DeleteRecord(object sender, GridRecordEventArgs e)
	{
		OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../App_Data/Northwind.mdb"));
		myConn.Open();
 
        OleDbCommand myComm = new OleDbCommand("DELETE FROM Suppliers WHERE SupplierID = @SupplierID", myConn);
 
        myComm.Parameters.Add("@SupplierID", OleDbType.Integer).Value = e.Record["SupplierID"];
		
        myComm.ExecuteNonQuery();
		myConn.Close();
	}
	void UpdateRecord(object sender, GridRecordEventArgs e)
	{
		OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../App_Data/Northwind.mdb"));
		myConn.Open();
 
        OleDbCommand myComm = new OleDbCommand("UPDATE Suppliers SET CompanyName = @CompanyName, Address = @Address, Country=@Country, HomePage=@HomePage WHERE SupplierID = @SupplierID", myConn);
 
        myComm.Parameters.Add("@CompanyName", OleDbType.VarChar).Value = e.Record["CompanyName"];
        myComm.Parameters.Add("@Address", OleDbType.VarChar).Value = e.Record["Address"];
        myComm.Parameters.Add("@Country", OleDbType.VarChar).Value = e.Record["Country"];
        myComm.Parameters.Add("@HomePage", OleDbType.VarChar).Value = e.Record["HomePage"];
        myComm.Parameters.Add("@SupplierID", OleDbType.Integer).Value = e.Record["SupplierID"];
        
        myComm.ExecuteNonQuery();
		myConn.Close();
	}
	void InsertRecord(object sender, GridRecordEventArgs e)
	{
		OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../App_Data/Northwind.mdb"));
		myConn.Open();        		
 
        OleDbCommand myComm = new OleDbCommand("INSERT INTO Suppliers (CompanyName, Address, Country, HomePage) VALUES(@CompanyName, @Address, @Country, @HomePage)", myConn);
 
        myComm.Parameters.Add("@CompanyName", OleDbType.VarChar).Value = e.Record["CompanyName"];
        myComm.Parameters.Add("@Address", OleDbType.VarChar).Value = e.Record["Address"];
        myComm.Parameters.Add("@Country", OleDbType.VarChar).Value = e.Record["Country"];
        myComm.Parameters.Add("@HomePage", OleDbType.VarChar).Value = e.Record["HomePage"];
        
        myComm.ExecuteNonQuery();
		myConn.Close();
	}
	void RebindGrid(object sender, EventArgs e)
	{
		CreateGrid();
	}
 
	</script>		
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html>
	<head>
		<title>obout ASP.NET Grid examples</title>
		<style type="text/css">
			.tdText {
				font:11px Verdana;
				color:#333333;
			}
			.option2{
				font:11px Verdana;
				color:#0033cc;
				background-color___:#f6f9fc;
				padding-left:4px;
				padding-right:4px;
			}
			a {
				font:11px Verdana;
				color:#315686;
				text-decoration:underline;
			}
 
			a:hover {
				color:crimson;
			}
		</style>	
		
		<script type="text/javascript">
 
				function LoadList()
		{
	        var listContainer= document.getElementById("LstBoxContainer");
	        var optListContainer=document.getElementById("optLstBox");
        	
	        optListContainer.appendChild(listContainer);
	        listContainer.style.display="block";
		
		}
		
		function SetValue(e)
		{
		    var cboText="";
            var checkList=document.getElementsByTagName("input");
 
            for(i=0;i<checkList.length;i++)
            {
                if(checkList[i].type.substr(0, 8) == 'checkbox')
                {
                    if(checkList[i].checked)
                    {
                        cboText+=document.getElementById(checkList[i].id).parentNode.childNodes[1].innerHTML +',';
                    }
                }
            }
            cbo1.text=cboText;
        
            if(cbo1.text.length > 0)
            {
                cbo1.setText(cbo1.text.substr(0, cbo1.text.length-1));
            }
		}
		
		
    </script>
			
	</head>
	<body>	
		<form runat="server">
					
		<obout:Grid id="grid1" runat="server" CallbackMode="true" Serialize="true" 
			AutoGenerateColumns="false"
			OnRebind="RebindGrid" OnInsertCommand="InsertRecord"  OnDeleteCommand="DeleteRecord" OnUpdateCommand="UpdateRecord">
			<ClientSideEvents OnClientEdit="LoadList" />
			<Columns>
				<obout:Column DataField="SupplierID" ReadOnly="true" HeaderText="ID" Width="60" runat="server"/>				
				<obout:Column DataField="CompanyName" HeaderText="Company Name" Width="250" runat="server">
				    <TemplateSettings TemplateID="TemplateCompanyName" HeaderTemplateID="TemplateCompanyName" />
				</obout:Column>
				<obout:Column DataField="Address" HeaderText="Address" Width="175" runat="server">
				    <TemplateSettings EditTemplateID="TemplateEditAddress" />
				</obout:Column>
				<obout:Column DataField="Country" HeaderText="Country" Width="400" runat="server">
				    <TemplateSettings EditTemplateID="TemplateEditCountry" />
				</obout:Column>
				<obout:Column DataField="HomePage" HeaderText="Has WebSite" Width="125" runat="server">
				    <TemplateSettings TemplateID="TemplateHasWebsite" EditTemplateID="TemplateEditHasWebsite" />
				</obout:Column>
				<obout:Column AllowEdit="true" AllowDelete="true" HeaderText="" Width="125" runat="server" />
			</Columns>
			<Templates>
				<obout:GridTemplate runat="server" ID="TemplateCompanyName">
					<Template>
						<b><u><i><%# Container.Value %></i></u></b>
					</Template>
				</obout:GridTemplate>
				<obout:GridTemplate runat="server" ID="TemplateEditAddress" ControlID="txtAddress" ControlPropertyName="value">
					<Template>
						<textarea rows="3" wrap="virtual" class="ob_gEC" id="txtAddress" style="overflow: auto;"></textarea>
					</Template>
				</obout:GridTemplate>
				<obout:GridTemplate runat="server" ID="TemplateHasWebsite" UseQuotes="true">
					<Template>
						<%# (Container.Value == "true" ? "yes" : "no") %>
					</Template>
				</obout:GridTemplate>
				<obout:GridTemplate runat="server" ID="TemplateEditHasWebsite" ControlID="chkHasWebsite" ControlPropertyName="checked" UseQuotes="false">
					<Template>
						<input type="checkbox" id="chkHasWebsite"/>
					</Template>
				</obout:GridTemplate>
				<obout:GridTemplate runat="server" ID="TemplateEditCountry" ControlID="ob_cbo1Textbox" ControlPropertyName="value">
					<Template>
					   <obout:Combobox ID="cbo1" runat="server" Width="310" CSSContainer="ob_ComboboxContainer"
                    ReadOnly="true" FolderStyle="../combobox/styles/default" AutoCloseEnable="False">
                    <CustomOptions>
                        <obout:Custom ID="Custom1" runat="server">
                            <div id="optLstBox" style="overflow:auto;height:200px;">
 
 
		<div id="LstBoxContainer" style="display: none; ">
                    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetCountries"
                        TypeName="TemplateData"></asp:ObjectDataSource>
                    <asp:CheckBoxList ID="CheckBoxList1" runat="server" CssClass="ob_gEC" DataTextField="CountryName" DataValueField="CountryID" Width="100%" DataSourceID="ObjectDataSource1">
                    </asp:CheckBoxList>
 
 
 
 
                            </div>
                        </obout:Custom>
                    </CustomOptions>
                </obout:Combobox>
					</Template>
				</obout:GridTemplate>
			</Templates>
		</obout:Grid>
		
 
                    
                </div>
		
		<asp:SqlDataSource runat="server" ID="sds1" SelectCommand="SELECT DISTINCT Country FROM Suppliers ORDER BY Country ASC"
		 ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb;" ProviderName="System.Data.OleDb"></asp:SqlDataSource>
 
		</form>
	</body>
</html>
<script type="text/javascript">
 function changeText()
 {
    cbo1.text = '';
    for(i = 1; i <= 5; i++)
    {
        var e = document.getElementById('chk' + i);
        if(e.checked)
        {
            cbo1.text += e.value + ',';
        }
    }
    if(cbo1.text.length > 0)
    {
        cbo1.text = cbo1.text.substr(0, cbo1.text.length-1);
    }
 }
</script>

Open in new window

0
Comment
Question by:german_martin
  • 6
  • 3
10 Comments
 
LVL 41

Expert Comment

by:guru_sami
ID: 24832144
Once you move your CBL into Item template of Gridview you can use RowDataBound event of GridView like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        CheckBoxList chbL = (CheckBoxList) e.Row.FindControl("CheckBoxList1");
          if(chbL !=null)
          {        chbL.Attributes.Add("onclick", "SetValue(this)");
           }
    }

Try something like above. The above code is not Tested...
 CheckBoxList CheckBoxList1 = (CheckBoxList)grid1.Templates[0].Container.FindControl("CheckBoxList1");
0
 

Author Comment

by:german_martin
ID: 24832188
I use your code (warning: i'm newby) and now I got this error

CS1061: 'System.EventArgs' no contiene una definición de 'Row' ni se encontró ningún método de extensión 'Row' que acepte un primer argumento de tipo 'System.EventArgs' (¿falta una directiva using o una referencia de ensamblado?)

You can view than error at:
http://024s0011/Grid/aspnet_templates_2.aspx
( http://024s0011/Grid/aspnet_templates_2.txt )

And here without your code:
http://024s0011/Grid/aspnet_templates_2.aspx
( http://024s0011/Grid/aspnet_templates_3.txt )

help!! Thanks!!! A lot!!!
0
 

Author Comment

by:german_martin
ID: 24832193
0
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 

Author Comment

by:german_martin
ID: 24832205
0
 
LVL 41

Accepted Solution

by:
guru_sami earned 250 total points
ID: 24832223
The error is because you added that code in Page_Load ...It should go in OnRowDataBound event handler...
<obout:Grid id="grid1" runat="server" CallbackMode="true" Serialize="true"
                  AutoGenerateColumns="false"
                  OnRebind="RebindGrid" OnInsertCommand="InsertRecord"  OnDeleteCommand="DeleteRecord" OnUpdateCommand="UpdateRecord">
This is your custom Grid so I am not sure if you have explicit OnRowDataBound event like you have above OnDeleteCommand, OnUpdateCommand, etc..
and corresponding to  those event you have
void UpdateRecord(object sender, GridRecordEventArgs e),
void DeleteRecord(object sender, GridRecordEventArgs e), etc.
Similarly I gave you code for...OnRowDataBound like:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

But since you have a custom Grid I am not sure what EventArgs it takes....you should adjust it accordingly...

The key is to find the contol inside RowDataBoundEvent...

0
 

Author Comment

by:german_martin
ID: 24832231
Thanks! let me try and i'm goin back in minutes with news
0
 

Author Comment

by:german_martin
ID: 24832290
Well, I'm soy stupid programming :( :(
Take a look again at http://oboutme.sytes.net/Grid/aspnet_templates_2.aspx ( http://oboutme.sytes.net/Grid/aspnet_templates_2.txt )
Tha page works but when I click on "edit" and next click on "Country (combobox)" the DIV id="LstBoxContainer" with the CheckBoxList doesn't appears

I have a FTP to make changes on that page
ftp://oboutme.sytes.net/ user:experts pass: 123+-
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 24832352
I see the code...but sorry at this point I am not able to get the reason why it is not showing the checkbox...
I know it has to do with how your custom gridView interprets your columns...

Also as I said earlier ...the code I gave is for a built-in asp.net gridview...so that exact code might not work as desired with CustomGridView....
I will look into you code and post if I find something or have any thing to clarify...
0
 

Author Comment

by:german_martin
ID: 24832375
Thank you so much

I have changed this:
protected void grid1_RowDataBound(object sender, GridViewRowEventArgs e)
protected void grid1_RowDataBound(object sender, GridRowEventArgs e)

And added in the control grid1 the next:
OnRowDataBound="grid1_RowDataBound"


But doesn't work too

In this other example:
http://oboutme.sytes.net/Grid/aspnet_templates_3.aspx the DIV id="LstBoxContainer" is out the Grid1 Control. It works perfectly with FireFox Mozilla but with IE the DIV loads in a wrong place (in the botton) I think IE have problems in the JS event LoadList, with the funcion appendChild in the line optListContainer.appendChild(listContainer);


thanks for helping anyway!!!
0
 
LVL 12

Expert Comment

by:starlite551
ID: 34425379
good solution!
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question