0

I have a GridView that currently brings up all records (all events from table Event). Now I want to add a dropdownbox that shows each Event and then a button. With the button click, the GridView will need to update with the data just for that event id.

I have attempted to do it but gotten issues. Below is my code that works, before issues. How would I implement the dropdown?

CURRENT ASP.NET CODE

<%@ Page Title="" Language="C#" MasterPageFile="~/admin/admin.master" AutoEventWireup="true" CodeFile="viewregistrant.aspx.cs" Inherits="admin_Default5" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RegistrantId"
OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" 
        EmptyDataText="No records has been added." CellPadding="4" ForeColor="#333333" 
        GridLines="None" AllowPaging="True" OnPageIndexChanging="PagingRegistrant_PageIndexChanging" AllowSorting="True">
    <AlternatingRowStyle BackColor="White" />
<Columns>
    <asp:TemplateField HeaderText="First Name" ItemStyle-Width="80">
        <ItemTemplate>
            <asp:Label ID="lblFirstName" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>'></asp:TextBox>
        </EditItemTemplate>

<ItemStyle Width="150px"></ItemStyle>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Last Name" ItemStyle-Width="80">
        <ItemTemplate>
            <asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>'></asp:TextBox>
        </EditItemTemplate>

        <ItemStyle Width="150px"></ItemStyle>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Address Line 1" ItemStyle-Width="80">
        <ItemTemplate>
            <asp:Label ID="lblAddressLine1" runat="server" Text='<%# Eval("AddressLine1") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtAddressLine1" runat="server" Text='<%# Eval("AddressLine1") %>'></asp:TextBox>
        </EditItemTemplate>

<ItemStyle Width="150px"></ItemStyle>
    </asp:TemplateField>
    <asp:CommandField ButtonType="Link" ShowEditButton="true" 
        ShowDeleteButton="true" ItemStyle-Width="150">
<ItemStyle Width="150px"></ItemStyle>
    </asp:CommandField>
</Columns>
    <EditRowStyle BackColor="#2461BF" />
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#EFF3FB" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F5F7FB" />
    <SortedAscendingHeaderStyle BackColor="#6D95E1" />
    <SortedDescendingCellStyle BackColor="#E9EBEF" />
    <SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</asp:Content>

CURRENT C# CODE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;


public partial class admin_Default5 : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this.BindGrid();
        }
    }

    private void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("spRegistrantsGridViewOld"))
            {
                cmd.CommandType = CommandType.StoredProcedure;  
                cmd.Parameters.AddWithValue("@Action", "SELECT");
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }
            }
        }
    }

    //Edit Button
    protected void OnRowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        this.BindGrid();
    }

    //Update Button
    protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = GridView1.Rows[e.RowIndex];
        int registrantId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
        string firstName = (row.FindControl("txtFirstName") as TextBox).Text;
        string lastName = (row.FindControl("txtLastName") as TextBox).Text;
        string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("spRegistrantsGridViewOld"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Action", "UPDATE");
                cmd.Parameters.AddWithValue("@RegistrantId", registrantId);
                cmd.Parameters.AddWithValue("@FirstName", firstName);
                cmd.Parameters.AddWithValue("@LastName", lastName);
                //cmd.Parameters.AddWithValue("@AddressLine1", addressLine1);
                //cmd.Parameters.AddWithValue("@AddressLine2", addressLine2);
                //cmd.Parameters.AddWithValue("@City", city);
                //cmd.Parameters.AddWithValue("@State", state);
                //cmd.Parameters.AddWithValue("@Zip", zip);
                //cmd.Parameters.AddWithValue("@Country", country);


                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        GridView1.EditIndex = -1;
        this.BindGrid();
    }

    //Cancel Edit Button
    protected void OnRowCancelingEdit(object sender, EventArgs e)
    {
        GridView1.EditIndex = -1;
        this.BindGrid();
    }

    //Delete Button
    protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int registrantId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
        string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("spRegistrantsGridViewOld"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Action", "DELETE");
                cmd.Parameters.AddWithValue("@RegistrantId", registrantId);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        this.BindGrid();
    }

    //JavaScript confirm delete
    //protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    //{
    //    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
    //    {
    //        (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
    //    }
    //}

    protected void PagingRegistrant_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
       GridView1.PageIndex = e.NewPageIndex; 
        DataBind();
    }

    protected void DropDownListEvent_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView1.DataBind();
    }
}

MY ATTEMPTS AT CODE THAT DIDN'T WORK BELOW... need some pointers here

And I know I need to add this somehow to fill the dropdownlist...

 if (!this.IsPostBack)
        {
            string events = DropDownListEvent.SelectedValue;

            using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
            {
                sqlConn2.Open();

                using (SqlCommand sqlCmd2 = new SqlCommand())
                {
                    sqlCmd2.Connection = sqlConn2;
                    sqlCmd2.CommandType = System.Data.CommandType.Text;

                    sqlCmd2.CommandType = System.Data.CommandType.StoredProcedure;
                    sqlCmd2.CommandText = "spGetAllEvents";

                    sqlCmd2.ExecuteNonQuery();

                    SqlDataReader sqlReader = sqlCmd2.ExecuteReader();

                    if (sqlReader.HasRows)
                    {
                        DropDownListEvent.DataSource = sqlReader;
                        DropDownListEvent.DataTextField = "EventName";
                        DropDownListEvent.DataValueField = "EventId";
                        DropDownListEvent.DataBind();
                    }

                    sqlConn2.Close();
                }

            }

And this to have it work after the button is clicked...

protected void ButtonChangeEvent_Click(object sender, EventArgs e)
    {
        string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Action", "SELECT");
                cmd.Parameters.Add("@EventId", SqlDbType.Int).Value = DropDownListEvent.SelectedValue;
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }
            }
        }

With the ASP of a dropdownlist and button...

Choose event:
    <asp:DropDownList ID="DropDownListEvent" runat="server">
    </asp:DropDownList>
    <asp:Button ID="ButtonChangeEvent" runat="server" 
        onclick="ButtonChangeEvent_Click" Text="Button" />

This attempt didn't work (as well as other attempts)... I am really desperate for some guidance to get this thing working. Thank you.

3
  • As I said, I don't know how to get a dropdown and button to work with a gridview. Commented Nov 19, 2015 at 13:15
  • @RockOn - Hey I guess you are trying to create the dropdownlist programmatically. If you want to show the dropdownlist when user edits the record, add it inside EditItemTemplate and bind that dropdown in RowDataBound event of gridview. Commented Nov 19, 2015 at 13:36
  • @Rahul Thanks how exactly would I do that? Commented Nov 19, 2015 at 13:44

1 Answer 1

1

As mentioned in the comment, add a dropdown list control in the EditItemTemplate tag like this:-

 <asp:TemplateField HeaderText="Events" ItemStyle-Width="80">
      <ItemTemplate>
         <asp:Label ID="lblEvent" runat="server" Text='<%# Eval("EventName") %>'>
         </asp:Label>
      </ItemTemplate>
      <EditItemTemplate>
          <asp:DropDownList ID="ddlEvents" runat="server" 
                            SelectedValue='<%# Eval("EventName") %>'></asp:DropDownList>
      </EditItemTemplate>
</asp:TemplateField>

Then, add the RowDataBoundEvent in your gridview:-

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
              OnRowDataBound="GridView1_RowDataBound"

In the code behind file, add the rowDataBound event handler method and find the dropdown we have added and bind it:-

protected void grdEmployees_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
       if (e.Row.RowState && DataControlRowState.Edit > 0)
       {
           DropDownList ddList= (DropDownList)e.Row.FindControl("ddlEvents");
           //Now call your ADO.NET code and bind the dropdownlist.
       }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.