Question to the experts. There is a gridview. Gridview

Output, insert and delete work. Insert algorithm

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)//список со всеми поломками { ((ListBox)GridView1.FooterRow.FindControl("ListBox2")).Items.Clear();//чистим второй список foreach (ListItem li in ((ListBox)GridView1.FooterRow.FindControl("ListBox1")).Items)//проходим по первому списку, где есть все элементы { if (li.Selected)//если элемент выбран { ((ListBox)GridView1.FooterRow.FindControl("ListBox2")).Items.Add(li.Text);//бросаем его во второй список для предпросмотра результата(вообще-то для предпросмотра можно использовать лейбл...) } } } protected void ListBox3_SelectedIndexChanged(object sender, EventArgs e)//список со всеми механиками { ((ListBox)GridView1.FooterRow.FindControl("ListBox4")).Items.Add(((ListBox)GridView1.FooterRow.FindControl("ListBox3")).SelectedItem.Text);//кидаем выбранного механика ((ListBox)GridView1.FooterRow.FindControl("ListBox3")).SelectedIndex = -1;//снимаем выделение, чтобы одного и того же можно было указать два раза подряд } protected void ListBox4_SelectedIndexChanged(object sender, EventArgs e)//дает возможность удалить механика в случае ошибки { ((ListBox)GridView1.FooterRow.FindControl("ListBox4")).Items.Remove(((ListBox)GridView1.FooterRow.FindControl("ListBox4")).SelectedItem); } string breakslist;//переменная для списка поломок, которая отправится в БД string workerslist;//переменная для списка механиков string priceslist;//для стоимостей ремонта каждой поломки protected void Insert_Click(object sender, EventArgs e)//кнопка добавления { breakslist = "";//предварительно обнуляем их на всякий случай workerslist = ""; priceslist = ((TextBox)GridView1.FooterRow.FindControl("TextBox1")).Text;//цены можно сохранить сразу foreach (ListItem li in ((ListBox)GridView1.FooterRow.FindControl("ListBox2")).Items)//пробегаем по второму списку { breakslist += li.Text + "<br/>";//и сохраняем из него все в одну переменную разделяя названия поломок тегом переноса } foreach (ListItem li in ((ListBox)GridView1.FooterRow.FindControl("ListBox4")).Items)//аналогично, как и с поломками { workerslist += li.Text + "<br/>"; } SqlDataSource1.InsertParameters["breakslist"].DefaultValue = breakslist; SqlDataSource1.InsertParameters["workerslist"].DefaultValue = workerslist; SqlDataSource1.InsertParameters["priceslist"].DefaultValue = priceslist; SqlDataSource1.Insert(); } 

Algorithm for retrieving list items from a saved variable

  foreach (GridViewRow Row in GridView1.Rows) { DataView dview = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty); breakslist = (String)dview.Table.Rows[Row.RowIndex]["breakslist"];//получаем переменную из БД for (int i = 0; i < breakslist.Length; i++)//посимвольно её перебираем { if (breakslist[i] != '<')//кидаем символы в строковую переменную пока не наткнемся на начало тега <br/> { formItem += breakslist[i]; } else//если же наткнулись, то сохраняем переменную как элемент списка и { ((ListBox)GridView1.Rows[Row.RowIndex].FindControl("ListBox6")).Items.Add(formItem); formItem = ""; i = i + 4;//и перескакиваем через тег бр } } } 

Question: where can I insert the second algorithm so that the list items are added to the list during editing?

In edit mode, I have no previously saved values.

Tried with RowDataBound and RowEditing, but failed. Received Null Reference Exception and ArgumentsOutOfRangeException , apparently not at that moment I was trying to add values. Asp code table attached

 <%@ Page Title="Чеки" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="checks.aspx.cs" Inherits="autorepair.checks" %> 

 <div> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:autorepairConnectionString %>" DeleteCommand="DELETE FROM [checks] WHERE [checkID] = @checkID" InsertCommand="INSERT INTO [checks] ([breakslist], [workerslist], [priceslist]) VALUES (@breakslist, @workerslist, @priceslist)" SelectCommand="SELECT * FROM [checks]" UpdateCommand="UPDATE [checks] SET [breakslist] = @breakslist, [workerslist] = @workerslist, [priceslist] = @priceslist WHERE [checkID] = @checkID"> <DeleteParameters> <asp:Parameter Name="checkID" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="breakslist" Type="String" /> <asp:Parameter Name="workerslist" Type="String" /> <asp:Parameter Name="priceslist" Type="String" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="breakslist" Type="String" /> <asp:Parameter Name="workerslist" Type="String" /> <asp:Parameter Name="priceslist" Type="String" /> <asp:Parameter Name="checkID" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:autorepairConnectionString %>" SelectCommand="SELECT [breakdownID], [breakname] FROM [breakdowns]"></asp:SqlDataSource> <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:autorepairConnectionString %>" SelectCommand="SELECT [workerID], [fullname] FROM [workers] WHERE [position]='Механик'"> </asp:SqlDataSource> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="checkID" DataSourceID="SqlDataSource1" AllowSorting="True" ShowFooter="True"> <Columns> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /> <asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="checkID"> <EditItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Eval("checkID") %>'></asp:Label> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("checkID") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:LinkButton ID="LinkButton1" OnClick="Insert_Click" runat="server">Добавить</asp:LinkButton> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Поломки" SortExpression="breakdown1"> <EditItemTemplate> <asp:ListBox ID="ListBox6" runat="server" Rows="5" Width="132px"></asp:ListBox> <asp:ListBox ID="ListBox5" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource2" DataTextField="breakname" DataValueField="breakdownID" Rows="5" SelectionMode="Multiple"></asp:ListBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("breakslist") %>'></asp:Label><br /> </ItemTemplate> <FooterTemplate> <asp:ListBox ID="ListBox2" runat="server" Rows="5" Width="132px"></asp:ListBox> <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource2" DataTextField="breakname" DataValueField="breakdownID" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" Rows="5" SelectionMode="Multiple"></asp:ListBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Механик" SortExpression="worker1"> <EditItemTemplate> <asp:ListBox ID="ListBox8" runat="server" AutoPostBack="True" Rows="5" Width="132px"></asp:ListBox> <asp:ListBox ID="ListBox7" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource3" DataTextField="fullname" DataValueField="workerID" Rows="5"></asp:ListBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("workerslist") %>'></asp:Label><br /> </ItemTemplate> <FooterTemplate> <asp:ListBox ID="ListBox4" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ListBox4_SelectedIndexChanged" Rows="5" Width="132px"></asp:ListBox> <asp:ListBox ID="ListBox3" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource3" DataTextField="fullname" DataValueField="workerID" OnSelectedIndexChanged="ListBox3_SelectedIndexChanged" Rows="5"></asp:ListBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Стоимость ремонта" SortExpression="price1"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Rows="5" Text='<%# Bind("priceslist") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label12" runat="server" Text='<%# Bind("priceslist") %>'></asp:Label><br /> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Rows="5"></asp:TextBox> </FooterTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> 

I would be very grateful))

1 answer 1

It worked like this. The left list is filled with the saved data, and the selected list items are highlighted in the right one. Now I do not know how to make it so that using the right list you can edit the left one as when inserting new records

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) { DataView dview = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty); breakslist = (String)dview.Table.Rows[e.Row.RowIndex]["breakslist"]; for (int i = 0; i < breakslist.Length; i++) { if (breakslist[i] != '<') { formItem += breakslist[i]; } else { ((ListBox)e.Row.FindControl("ListBox6")).Items.Add(formItem); formItem = ""; i = i + 4; } } foreach (ListItem ItemToSelect in ((ListBox)e.Row.FindControl("ListBox5")).Items) { foreach (ListItem SavedItem in ((ListBox)e.Row.FindControl("ListBox6")).Items) { if (ItemToSelect.Text == SavedItem.Text) { ItemToSelect.Selected = true; } } } } } }