Редактирование вида сетки — проблема с выпадающим списком

#asp.net #gridview #aspxgridview

#asp.net #просмотр сетки #aspxgridview

Вопрос:

У меня есть представление сетки, и я пытаюсь создать выпадающий список в режиме редактирования представления сетки. В представлении сетки отображаются пользователи в моем проекте, и я хочу, чтобы выпадающий список позволял им изменять свой город из таблицы городов в моей базе данных. Я пытался использовать редактирование шаблона в соответствии с видео, которое я видел на YouTube (https://www.youtube.com/watch?v=YB2pe_C2Tbgamp;t=191samp;ab_channel=MukeshChaudhary ). Хотя я получаю сообщение об ошибке:

System.Data.OleDb.OleDbException: «Вы не можете добавить или изменить запись, потому что в таблице «города» требуется связанная запись».

Код позади

 using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RapidTyper.App_Code;

public partial class ManagerChange : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack) PopulateGrid();
    }

    private DataSet GetData()
    {
        UserService UserService = new UserService();
        return UserService.GetUsers();
    }
    private void PopulateGrid()
    {
        GridView1.DataSource = GetData();
        GridView1.DataBind();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        PopulateGrid();
    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;

        PopulateGrid();
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        User userDetaling = new User();
        userDetaling.setFName(((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text);
        userDetaling.setLName(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text);
        userDetaling.setID(GridView1.Rows[e.RowIndex].Cells[2].Text);
        userDetaling.setBirthDate(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);

        userDetaling.setAddress(((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text);
        userDetaling.setZipCode (((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text);
        userDetaling.setEmail(((TextBox)GridView1.Rows[e.RowIndex].Cells[7].Controls[0]).Text);
        userDetaling.setPassword(((TextBox)GridView1.Rows[e.RowIndex].Cells[8].Controls[0]).Text);

        UserService UserService = new UserService();
        UserService.UpdateUser(userDetaling);
        GridView1.EditIndex = -1;
        PopulateGrid();
    }
}
 

Aspx

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" style="margin-top: 21px">
    <Columns>
        <asp:BoundField DataField="fName" HeaderText="Name" />
        <asp:BoundField DataField="lName" HeaderText="Last Name" />
        <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" />
        <asp:BoundField DataField="birthDate" HeaderText="Birth Date" />
             
        <asp:TemplateField HeaderText="city">
            <EditItemTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="cityName" DataValueField="cityNum">
                </asp:DropDownList>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT * FROM [cities]"></asp:SqlDataSource>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("cityName") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
             
        <asp:BoundField DataField="address" HeaderText="address" />
        <asp:BoundField DataField="zipcode" HeaderText="zip code" />
        <asp:BoundField DataField="email" HeaderText="email" />
        <asp:BoundField DataField="userPassword" HeaderText="password" />
        <asp:CommandField ButtonType="Button" HeaderText="Edit" ShowEditButton="True" />
    </Columns>
    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
    <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#FFF1D4" />
    <SortedAscendingHeaderStyle BackColor="#B95C30" />
    <SortedDescendingCellStyle BackColor="#F1E5CE" />
    <SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
 

Комментарии:

1. Похоже, что ваша таблица городов имеет отношение к другой таблице, и когда город изменяется, это отношение нарушается. В какой момент возникает эта ошибка?

2. Когда я редактирую выпадающий список

3. Что вы подразумеваете под редактированием ? Вы просто выбираете город или пытаетесь добавить город. Вы не сможете просто добавить новый.