Link to home
Start Free TrialLog in
Avatar of german_martin
german_martin

asked on

Add onclick attribute to CheckBoxList inside another control

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

Avatar of guru_sami
guru_sami
Flag of United States of America image

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");
Avatar of german_martin
german_martin

ASKER

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!!!
ASKER CERTIFIED SOLUTION
Avatar of guru_sami
guru_sami
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks! let me try and i'm goin back in minutes with news
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+-
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...
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!!!
good solution!