开发者

Selecting only one item from a class

开发者 https://www.devze.com 2023-02-27 09:52 出处:网络
I have a GridView that has an <asp:Label> in it with ID=\"Description\" and CssClass=\"dsc\". In my C#.net codebehind the aspx file, I have a data table that has the addresses and descriptions f

I have a GridView that has an <asp:Label> in it with ID="Description" and CssClass="dsc". In my C#.net code behind the aspx file, I have a data table that has the addresses and descriptions from a database, I am populating a Google Map with the Lat/Lng coods that are converted from the address with the little Google Markers. When the marker is clicked, the description for that address pops up above the marker. This is working fine.

Now for the hard part, I am trying to add the same description to each row in the GridView, uniquely. Does that make sense? When a row is clicked (each row will have a title, which is the description from the db), the description needs to open up above the marker in the Google map. Each row in the GridView will have their own description and address.

Here is my code so far:

public partial class NEW_controls_RoadsAndBridges : System.Web.UI.UserControl
{
    private SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getInfo();
        }
    }



    protected void getInfo()
    {
        try
        {
            conn.Open();
            ///
            ///Check to see if connection is good
            ///
            string selectString = "SELECT Address, Description, Date, Lat, Long FROM D2_ReportAProblemForm ORDER BY id DESC";
            SqlCommand cmd = new SqlCommand(selectString, conn);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            DataTable dt = new DataTable();
            adapter.Fill(dt);
            BuildScript(dt);
            cmd.Dispose();

            //If successful 
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        catch (SqlException sqle)
        {
            //if error
            // Response.Redirect("ReportAProblemInfo.aspx?info=fail");
        }
        finally
        {
            if (conn != null)
                conn.Close();
        }
    }



    private void BuildScript(DataTable tbl)
    {
        String Locations = "";
        String Description =开发者_StackOverflow "";
        String Address = "";
        String java = "";
        String java2 = "";
        int n = 0;
        foreach (DataRow r in tbl.Rows)
        {
            string Latitude = r["Long"].ToString();
            string Longitude = r["Lat"].ToString();
            Description = r["Description"].ToString();
            Address= r["Address"].ToString();
            string marker = "marker" + n.ToString();
            // create a line of JavaScript for marker on map for this record 
            Locations += Environment.NewLine + "var "+marker+@"=new GMarker(new GLatLng(" + Latitude + "," + Longitude + ")); map.addOverlay("+marker+@");";

            java += @"GEvent.addListener(" + marker + @", 'click', function() 
                    {
                        " + marker + @".openInfoWindowHtml('" + Description + @"');
                        map.checkResize();
                        map.setCenter(" + marker + @");
                    });";
            java2 += marker+@".openInfoWindowHtml('" + Description + @"');
                        map.checkResize();
                        map.setCenter("+marker+@");";

            n++;
        }

        // construct the final script
        js.Text =
            @"<script type='text/javascript'>
            function initialize() 
            {
                if (GBrowserIsCompatible()) 
                {
                    var map = new GMap2(document.getElementById('map_canvas'),{ size: new GSize(350,300) } ); 
                    map.checkResize();
                    map.setCenter(new GLatLng(35.347769,-98.05),8); 
                    map.openInfoWindow(map.getCenter(), document.createTextNode('Hello')); 
                     " + Locations + java + @"


                    $(document).ready(function(){
                        $('.dsc').css('cursor','pointer');
                        $('.dsc').each(function( intIndex ) {
                            $(this).bind ('click',function() {
                                 " + java2 + @"
                            });
                        });
                         });

                    map.setUIToDefault();
                }
            }
            </script> ";
    }
    protected void GridView1_DataBound(object sender, EventArgs e)
    {

        string selectString = "SELECT Address, Description, Date, Lat, Long FROM D2_ReportAProblemForm ORDER BY id DESC";
        SqlCommand cmd = new SqlCommand(selectString, conn);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable();
        adapter.Fill(dt);

        String Locations = "";
        String Description = "";
        String java2 = "";
        int n = 0;
        foreach (DataRow r in dt.Rows)
        {
            string Latitude = r["Long"].ToString();
            string Longitude = r["Lat"].ToString();
            Description = r["Description"].ToString();
            string marker = "marker" + n.ToString();
            // create a line of JavaScript for marker on map for this record 
            Locations += Environment.NewLine + "var " + marker + @"=new GMarker(new GLatLng(" + Latitude + "," + Longitude + ")); map.addOverlay(" + marker + @");";

            java2 += marker + @".openInfoWindowHtml('" + Description + @"');
                        map.checkResize();
                        map.setCenter(" + marker + @");";

            n++;
            js2.Text = @"<script type='text/javascript'>
                    {
                        $('.dsc').click(function()
                        {
                            " + java2 + @"
                    }
                    </script> ";
        }//end foreach



    }//end _DataBound

}

There are two <asp:Literal> with IDs js and js2 so I can put jQuery/JavaScript right into the C# code.

GridView code:

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
    ondatabound="GridView1_DataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <table width="500px">
                    <tr style="background-color: #dcdcdc;" >
                        <td colspan="2" style="text-align: left; font-weight: bold; font-size: 14xp;">
                        <asp:Label ID="Description" CssClass="dsc" runat="server" Text='<%#Eval ("Description") %>'></asp:Label>
                        </td>
                    </tr>
                    <tr style="text-align: left; font-weight: lighter; font-size: 12px;">
                        <td>
                        <%#Eval ("Address") %>
                        </td>
                        <td>
                        <%#Eval ("Date") %>
                        </td>
                    </tr>
                </table>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

PLEASE help me figure this one out, I have been on this one part for a week and I am completely stumped. Thanks guys!


Okay, I think I see the problem. You have this:

foreach (DataRow r in dt.Rows){
...
   js2.Text = @"<script type='text/javascript'>
                    {
                        $('.dsc').click(function()
                        {
                            " + java2 + @"
                    }
                    </script> ";
}//end foreach

The problem is that each iteration of the loop is wiping out what you had done in the previous. js2.Text= says set the text equal to this string, replacing what was already in it.

Now, issue #2. Your jquery is as follows:

$('.dsc').click(function()

The problem here is that this will apply to every one of your rows since each one has the class dsc. So even if you fix problem #1 by changing the text= to a text+=, your code will still not work.

You have 2 options that I can see. First, you can assign a distinct ID to each label in addition to the class. Then for each row your code could be $('#myID1').click..., where myID1 is a uniquely generated ID for each row. Be careful if you do it this way as .net likes to generate big ugly IDs that aren't what you might think they will be.

The other option, and the one I would prefer is to just add the onclick directly to the label. I think you should be able to just grab the label while in that foreach you have in your databound method. Then you do something similar to this:

theLabel.Attributes.Add("onclick", java2);

May require some slight tweak to java2, I didn't look at it in full detail, but this way the onclick will just be attached directly to the label on initial load without any javascript to add it.

0

精彩评论

暂无评论...
验证码 换一张
取 消