Member 11759154 Ответов: 1

Выпадающий список sectedvalue не работает


Я попытался выбрать дату рождения из выпадающего списка по выбранным месяцам, но не выбрал значение. Вот код asp.net и код C#

asp.net
<div> <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Height="32px" Width="250px" AutoPostBack="true" >
                             <asp:ListItem Value="0">Select All</asp:ListItem>
                             <asp:ListItem Value="1">January</asp:ListItem>
                             <asp:ListItem Value="2">February</asp:ListItem>
                             <asp:ListItem Value="3">March</asp:ListItem>
                             <asp:ListItem Value="4">April</asp:ListItem>
                             <asp:ListItem Value="5">May</asp:ListItem>
                             <asp:ListItem Value="6">Jun</asp:ListItem>
                             <asp:ListItem Value="7">July</asp:ListItem>
                             <asp:ListItem Value="8">August</asp:ListItem>
                             <asp:ListItem Value="9">September</asp:ListItem>
                             <asp:ListItem Value="10">October</asp:ListItem>
                             <asp:ListItem Value="11">November</asp:ListItem>
                             <asp:ListItem Value="12">December</asp:ListItem>
                                    </asp:DropDownList> </div>

<div>  <asp:GridView AutoGenerateColumns="False" ID="GridView1" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="GridView1_PageIndexChanging"
                     runat="server" Width="100%" Font-Size="Medium" CellPadding="4" ForeColor="#333333" GridLines="None" >
<AlternatingRowStyle BackColor="White" />
                    <Columns>
                        <asp:TemplateField HeaderText=" BirthDay" ItemStyle-HorizontalAlign="left"> <ItemTemplate>
<asp:Label ID="lbldep" runat="server" Text='<%#Eval ("Birthday" ,"{0:MMMM}")%>'></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%#Eval ("Birthday", "{0:MMMM dd (ddd)}") %>'></asp:Label>
 <span style="color:silver">Office Phone:</span> <asp:label id="lblphone" Text = '<%# Eval("BusinessPhone") %>' runat="server"/>
 <asp:Panel ID="Panel1" runat="server" Visible='<%# Eval ("Photo") != DBNull.Value %>'><a class='fancybox' href='/images/employee_photos/<%#Eval("Photo") %>' title='<%# Eval("First_Name") %>'></a></asp:Panel>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Last_Name")%>'></asp:Label>
<asp:Label ID="lblFirstname" runat="server" Text='<%#Eval("First_Name")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>         
                    </asp:GridView>


Что я уже пробовал:

Код C#

public partial class TestFilterMonth : System.Web.UI.Page
    {
        static string constr = ConfigurationManager.ConnectionStrings["IntranetConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        protected void Page_Load(object sender, EventArgs e)
        {
            BindGrid();
        }
        private void BindGrid()
        {
            DataSet ds = new DataSet();
            string query = "SELECT Employee.Photo, convert(datetime, (convert(varchar(2), month(Birthday)) + '/' + " +
                            "convert(varchar(2), day(Birthday)) + '/' + " +
                            "convert(varchar(4), year(getdate())))) AS Birthday, " +
                           " Employee.First_Name, Employee.Last_Name, Employee.BusinessPhone," +
             "Employee.First_Name, Employee.Last_Name, Employee.BusinessPhone " +
             " From Employee WHERE  Birthday IS NOT NULL Order By Birthday";

            SqlCommand cmd = new SqlCommand(query, con);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            if (query != null)
            {
                da.Fill(ds);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();
            }


        }
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {

            try
            {
                
                string query = "SELECT Employee.Photo, convert(datetime, (convert(varchar(2), month(Birthday)) + '/' + " +

                             "convert(varchar(4), year(getdate())))) AS Birthday, " +
                             " Employee.First_Name, Employee.Last_Name, Employee.BusinessPhone," +
               "Employee.First_Name, Employee.Last_Name, Employee.BusinessPhone " +
               " From Employee WHERE Birthday = '" + DropDownList1.SelectedValue + "'";
               
                SqlCommand cmd = new SqlCommand(query, con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
                if (DropDownList1.SelectedIndex == 0)
                {
                    BindGrid();
                }
                else if (DropDownList1.SelectedIndex == 1)
                {
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
                else if (DropDownList1.SelectedIndex == 2)
                {
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }

            }
            catch
            {
                string message = DropDownList1.SelectedItem.Text + " - " + DropDownList1.SelectedItem.Value;
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + message + "');", true);
            }
        }
       
       
        public void GridView1_PageIndexChanging(Object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindGrid();

        }
    }

1 Ответов

Рейтинг:
0

Richard Deeming

Цитата:
" From Employee WHERE Birthday = '" + DropDownList1.SelectedValue + "'"

Основываясь на вашем предыдущем запросе, Birthday столбец содержит значение даты, представляющее дату рождения сотрудника. Вы пытаетесь сравнить это значение даты с целым числом, но это не сработает.

Вам нужно выбрать строки, где Month(Birthday) равно выбранному значению.

Но вам также нужно исправить SQL-инъекция[^] уязвимость в вашем коде.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    const string query = "SELECT Employee.Photo, "
                       + " convert(datetime, (convert(varchar(2), month(Birthday)) + '/' + convert(varchar(4), year(getdate())))) AS Birthday, "
                       + " Employee.First_Name, Employee.Last_Name, Employee.BusinessPhone,"
                       + " Employee.First_Name, Employee.Last_Name, Employee.BusinessPhone "
                       + " From Employee WHERE month(Birthday) = @month";
    
    int month;
    int.TryParse(DropDownList1.SelectedValue, out month);
    if (month == 0)
    {
        BindGrid();
        return;
    }
    
    using (var connection = new SqlConnection(constr))
    using (var command = new SqlCommand(query, connection))
    {
        command.Parameters.AddWithValue("@month", month);
        
        var da = new SqlDataAdapter(command);
        var dt = new DataTable();
        da.Fill(dt);
        
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}



Все, что вы хотели знать о SQL-инъекции (но боялись спросить) | Трой Хант[^]
Как я могу объяснить SQL-инъекцию без технического жаргона? | Обмен Стеками Информационной Безопасности[^]
Шпаргалка по параметризации запросов / OWASP[^]


ZurdoDev

+5