【问题标题】:Selecting only one item from a class从类中仅选择一项
【发布时间】:2011-08-10 09:24:39
【问题描述】:

我有一个 GridView,其中有一个 <asp:Label>,ID="Description" 和 CssClass="dsc"。在我的 aspx 文件后面的 C#.net 代码中,我有一个数据表,其中包含来自数据库的地址和描述,我正在使用从带有小 Google 标记的地址转换而来的经纬度坐标填充 Google 地图。单击标记时,该地址的描述会在标记上方弹出。这工作正常。

现在对于困难的部分,我正在尝试为 GridView 中的每一行添加相同的描述,唯一。那有意义吗?当点击一行时(每一行都有一个标题,这是来自数据库的描述),描述需要在谷歌地图中的标记上方打开。 GridView 中的每一行都有自己的描述和地址。

到目前为止,这是我的代码:

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 = "";
        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

}

有两个 &lt;asp:Literal&gt;,ID 分别为 jsjs2,所以我可以将 jQuery/JavaScript 直接放入 C# 代码中。

GridView 代码:

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

请帮我解决这个问题,我已经在这个部分工作了一周,我完全被难住了。 谢谢大家!

【问题讨论】:

  • 我看到了一个矛盾的术语。 '对每个都有相同的描述' ...'唯一''有自己的描述''there is 2 with ids js and js2 so I can put jquery/javascript right into the c# code'是什么意思?
  • 您在此处包含了很多代码,但描述并没有提供足够的信息来告诉我们您期望什么行为,以及您将获得什么行为。
  • 先生。失望:“对每个人的描述相同”表示单击标记 A 或单击 A 行时显示的描述相同。这有意义吗?使用 asp:Literal,我的意思是我有两个 asp:Literal 控件,我相信它们被称为控件?,我用来将我的 javascript 代码放入其中。他们的 id 是 js 和 js2。
  • StriplingWarrior:发生的情况是,当我单击 GridView 中的任何行时,从数据库加载的最后一个描述显示在标记上方。我的数据表中有 2 行,第一行有描述“Test”,第二行有描述“Test2”。当我单击 gridview 中应显示描述“Test”的行时,会显示“Test2”。如果您单击网格视图中的另一行,“Test2”也会显示。这有意义吗?
  • 您可能希望包含您的 gridview 标记。我怀疑问题可能出在那儿。

标签: jquery asp.net database gridview datatable


【解决方案1】:

好的,我想我看到了问题所在。你有这个:

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

问题是循环的每一次迭代都会抹去你之前所做的事情。 js2.Text= 表示将文本设置为等于该字符串,替换其中已有的内容。

现在,问题 #2。你的jquery如下:

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

这里的问题是这将适用于你的每一行,因为每一行都有类 dsc。因此,即使您通过将 text= 更改为 text+= 来解决问题 #1,您的代码仍然无法正常工作。

我可以看到您有 2 个选项。首先,除了类之外,您还可以为每个标签分配一个不同的 ID。然后对于每一行,您的代码可能是$('#myID1').click...,其中 myID1 是为每一行生成的唯一 ID。如果你这样做,请小心,因为 .net 喜欢生成大而丑陋的 ID,而这些 ID 并不是你想象的那样。

另一个选项,我更喜欢的选项是将 onclick 直接添加到标签。我认为您应该能够在数据绑定方法中的 foreach 中抓取标签。然后你做类似这样的事情:

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

可能需要对 java2 进行一些细微的调整,我没有详细查看它,但是这样 onclick 将在初始加载时直接附加到标签上,而无需添加任何 javascript。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    相关资源
    最近更新 更多