2013-07-09 4 views
0

У меня есть странная проблема. У меня есть страница asp.net, в которой у меня есть dropdownlist/combobox, привязанный к таблице SQL. Выпадающий список настроен на отображение поля первичного ключа, которое является просто увеличивающимся числом, начинающимся с 1.asp.net dropdownlist сброс

У меня была вся форма, работающая отлично, но теперь я сталкиваюсь с некоторыми проблемами. Я сузил проблему до выпадающего списка, кнопки и кнопок события onClick. Когда я нажимаю кнопку, выпадающий список сбрасывается на номер 2. В настоящее время в моей таблице sql есть только 3 элемента и, следовательно, только 3 числа (1,2,3) в моем выпадающем списке. Если я устанавливаю список на номер 1 и нажимаю кнопку, он остается на номер 1. Если я установил его на 2, он останется на втором. Если я установил его на что-либо выше 2, он всегда сбрасывается до 2. Я фактически удалил все строки кода в клике, чтобы щелчок кнопки буквально ничего не делал, но он все же сбрасывается до 2, если выбранный элемент выше этого.

Вот мой код HTML. Im включая все это в том случае, проблема в другом:

<%@ Page Language="vb" AutoEventWireup="false" CodeFile="SGC.aspx.vb" Inherits="sgc" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
<title></title> 
<style type="text/css"> 
    .auto-style1 { 
     width: 181px; 
    } 
    .auto-style2 { 
     width: 1px; 
    } 
    .auto-style3 { 
     width: 14px; 
    } 
    .auto-style4 { 
    } 
    .auto-style5 { 
     height: 23px; 
    } 
    .auto-style6 { 
     width: 181px; 
     height: 23px; 
    } 
    .auto-style7 { 
     width: 4px; 
    } 
    .auto-style10 { 
     width: 182px; 
     height: 23px; 
    } 
    .auto-style11 { 
     width: 302px; 
     height: 23px; 
    } 
    .auto-style13 { 
     width: 14px; 
     height: 23px; 
    } 
</style> 
</head> 
<body style="background-image:URL(/idle_screen.jpg);"> 

<form id="form1" runat="server"> 
<div> 
    <table align="center" style="width: 100%;"> 
    <tr> 
     <td class="auto-style6" ></td> 
     <td class="auto-style5" bgcolor="#FF0000" colspan="3" align="center"> 
      <asp:Label ID="Label2" runat="server" Font-Names="Arial Black" Font-Size="Large" ForeColor="#003399" Text="SGC Message Log"></asp:Label> 
     </td> 
     <td class="auto-style13"></td> 
    </tr> 
    <tr> 
     <td class="auto-style1">&nbsp;</td> 
     <td class="auto-style4"> 
      <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" SelectCommand="select sub_id 'ID #', race 'Race', orgMsg 'Original Message', Case when replyMsg like '%' then 'See Reply' else 'Reply' end as Reply, androidID from messages"></asp:SqlDataSource> 
     </td> 
     <td>&nbsp;</td> 
     <td class="auto-style2">&nbsp;</td> 
     <td class="auto-style3">&nbsp;</td> 
    </tr> 
    <tr> 
     <td class="auto-style6"></td> 
     <td class="auto-style7" colspan="3" rowspan="2"> 
     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" align="center" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataKeyNames="ID #" DataSourceID="SqlDataSource2" EnableModelValidation="True" GridLines="Vertical" Width="1400px"> 
       <AlternatingRowStyle BackColor="#DCDCDC" /> 
       <Columns> 
        <asp:BoundField DataField="ID #" HeaderText="ID #" InsertVisible="False" ReadOnly="True" SortExpression="ID #" /> 
        <asp:BoundField DataField="Race" HeaderText="Race" SortExpression="Race" /> 
        <asp:BoundField DataField="Original Message" HeaderText="Original Message" SortExpression="Original Message" /> 
        <asp:BoundField DataField="Reply" HeaderText="Reply" ReadOnly="True" SortExpression="Reply" /> 
        <asp:BoundField DataField="androidID" HeaderText="androidID" SortExpression="androidID" /> 
       </Columns> 
       <FooterStyle BackColor="#CCCCCC" ForeColor="Black" /> 
       <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" /> 
       <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" /> 
       <RowStyle BackColor="#EEEEEE" ForeColor="Black" /> 
       <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" /> 
      </asp:GridView> 

     </td> 
     <td class="auto-style10"></td> 
    </tr> 
    <tr> 
     <td class="auto-style6"></td> 
     <td class="auto-style10"></td> 
    </tr> 
    <tr> 
     <td class="auto-style6"></td> 
     <td class="auto-style11"></td> 
     <td class="auto-style5"></td> 
     <td class="auto-style5"></td> 
     <td class="auto-style5"></td> 
    </tr> 
    <tr> 
     <td class="auto-style6">&nbsp;</td> 
     <td class="auto-style4" bgcolor="#FF0000" align="center" colspan="3"> 
      <asp:Button ID="Button1" runat="server" OnClick="MyButton_Click" Text="Refresh" Width="175px" ForeColor="#003399" /> 
      </td> 
     <td class="auto-style10">&nbsp;</td> 
    </tr> 
</table> 
    <asp:Panel ID="Panel1" runat="server" Width="902px"> 

    </asp:Panel> 
     <asp:Panel ID="Panel2" runat="server"> 
      &nbsp;&nbsp; 
      <asp:Label ID="Label1" runat="server" Text="Label" Enabled="False" Visible="False"></asp:Label> 
     </asp:Panel> 

</div> 
<div> 
<asp:DropDownList ID="deviceList" runat="server" DataSourceID="SqlDataSource2" DataTextField="ID #" DataValueField="androidID" AppendDataBoundItems="true"> 

</asp:DropDownList> 
<br /><br /> 
<asp:TextBox ID="txtPayload" runat="server" Width="750px" Height="120px" TextMode="MultiLine"></asp:TextBox> 
<br /><br /> 
<asp:Button ID="btnPush" runat="server" Text="Send" OnClick="sendtxt" /> 
<asp:Label ID="lblResponse" runat="server" Text=""></asp:Label> 
</div></form> 
</body> 
</html> 

я не включил какой-либо из моего кода Visual Basic, так как ни один из них не кажется, никакого эффекта. Если кто-то подумает, что это необходимо, я был бы рад опубликовать его. Кто-нибудь знает, почему выбранный индекс моего списка будет сброшен (но только выше 2) при нажатии кнопки, которая ничего не делает?

Update

Вот весь мой VB файл кода. Я все вернул туда, где это должно быть.

Imports System.Net 
Imports System.IO 
Imports System.Security.Cryptography.X509Certificates 
Imports System.Net.Security 
Imports System.Web 
Imports System.Web.Services 
Imports System.Web.Services.Protocols 
Imports System.Data 
Imports System.Data.SqlClient 

Public Class sgc 
Inherits System.Web.UI.Page 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 

End Sub 

Protected Sub MyButton_Click(sender As Object, e As EventArgs) 

    ''''  
    Response.Redirect(Request.RawUrl) 

End Sub 



Private Function SendNotification(ByVal authstring As String) As String 

    Dim request As WebRequest = WebRequest.Create("https://android.googleapis.com/gcm/send") 
    request.Method = "POST" 
    request.ContentType = "application/x-www-form-urlencoded" 
    request.Headers.Add(String.Format("Authorization: key={0}", authstring)) 
    Dim collaspeKey As String = Guid.NewGuid().ToString("n") 
    Dim deviceList As DropDownList = FindControl("deviceList") 
    Dim DGridView As GridView = FindControl("GridView1") 
    Dim txtPayload As TextBox = FindControl("txtPayload") 
    Dim i As Integer = Convert.toInt32(deviceList.Selecteditem.text) 
    Dim reply As String = txtPayload.Text 
    Dim race As String = DGridView.Rows(i).Cells(1).Text 
    Dim orgm As String = DGridView.Rows(i).Cells(2).Text 

    Dim payload As String = race + ";" + orgm + ";" + reply 
    Dim postData As String = String.Format("registration_id={0}&data.payload={1}&collapse_key={2}", deviceList.SelectedValue, payload, collaspeKey) 
    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData) 
    request.ContentLength = byteArray.Length 
    Dim dataStream As Stream = request.GetRequestStream() 
    dataStream.Write(byteArray, 0, byteArray.Length) 
    dataStream.Close() 
    Dim response As WebResponse = request.GetResponse() 
    dataStream = response.GetResponseStream() 
    Dim reader As New StreamReader(dataStream) 
    Dim responseFromServer As String = reader.ReadToEnd() 
    reader.Close() 
    dataStream.Close() 
    response.Close() 

    Return responseFromServer 
End Function 

Protected Sub sendtxt(sender As Object, e As System.EventArgs) 
    Dim txtPayload As TextBox = FindControl("txtPayload") 
    Dim lblResponse As Label = FindControl("lblResponse") 
    Dim deviceList As DropDownList = FindControl("deviceList") 

    lblResponse.Text = "Message Sent. Confirmation " + SendNotification("My Auth Key") 


    txtPayload.text = "" 

End Sub 
End Class 

Update 2

Я изменил мой код, чтобы сделать все связывание себя в VB. Это до сих пор, кажется, не помогло:

If Not Page.IsPostBack Then 

     Dim sqlds As SqlDataSource = New SqlDataSource() 
     sqlds.ID = "SqlDataSource3" 
     Me.Page.Controls.Add(sqlds) 
     sqlds.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString2").ConnectionString 
     sqlds.SelectCommand = "select sub_id 'ID #', race 'Race', orgMsg 'Original Message', Case when replyMsg like '%' then 'See Reply' else 'Reply' end as Reply, androidID from messages" 
     GridView1.DataSource = sqlds 
     GridView1.DataBind() 
     deviceList.DataSourceID = "SqlDataSource2" 
     deviceList.DataTextField = "ID #" 
     deviceList.DataValueField = "androidID" 
     deviceList.DataBind() 

    End If 

Благодаря

+0

Сообщите свое кодовое слово, все, пожалуйста. –

+0

Ну, нажатие кнопки не делает ничего. По крайней мере, это вызывает обратную передачу, что означает, что ваша страница будет повторно отображена со всем, что влечет за собой. Без кода вы не можете сказать, что происходит – fnostro

+0

Спасибо, что нашли время ответить. Я довольно новичок в asp.net, поэтому не полностью понимаю все различия между обычным программированием на рабочем столе, к которому я привык. Я опубликовал свой код – Chris2222000

ответ

1

вам просто нужно проверить постбэк на Pageload случае вашей.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 

    If Me.IsPostBack Then Return 

End Sub 
+0

Это, похоже, не сработало.Выброс все еще сбрасывается – Chris2222000

+0

с использованием 'SQLDataSource' является обязательным? если нет, я рекомендую вам связать выпадающий список с кодом и вызвать эту функцию на 'page_load'' Event', только если выполнен «postback» –

+0

Нет, это необязательно. Я пробовал привязать оба пути. С кодом и без него. Он всегда делает то же самое. Спасибо за вашу дальнейшую помощь. Есть ли способ, с помощью которого я могу полностью отключить обратную связь и только вызывать его вручную? Это форма, которую я буду использовать, чтобы не было огромной сделки. – Chris2222000