简体   繁体   中英

Question about Gridview and data in Asp.net with C#

I'm making a module to save an array in an SQL database. For example, I want to save (889,4,01/12/2021) , (889,4,02/12/2021) , and (889,4,03/12/2021) .

I'm using a gridview where I obtain the first value ( 889 ). Then I get the date with a textbox and I run a query to return the dates in rows and are stored in a gridview.

I'm trying to choose the 2nd gridview value ( date ) with GridView2.Rows[0].Cells[1].Text , but is outside of the range of valid values.

As this is an array, I save all the SQL sentences in a textbox an later I execute, so that is my code

string[,] arreglo = new string[GridView1.Rows.Count, 7];
foreach (GridViewRow row in GridView1.Rows)
{
    CheckBox chkbox1 = (CheckBox)row.FindControl("chkActive");
    if (chkbox1.Checked)
    {
        arreglo[row.RowIndex, 0] = GridView1.Rows[row.RowIndex].Cells[1].Text;
        string[,] array = new string[GridView2.Rows.Count, 2];
        foreach (GridViewRow col in GridView2.Rows)
            array[col.RowIndex, 0] = GridView2.Rows[col.RowIndex].Cells[1].Text;
        txtInsert.Text = txtInsert.Text + "insert into  T_USUARIO_dETALLE(id_usuario,campana,fecha,fecha_carga,id_superv,estado_dotacion) values ('" + arreglo[row.RowIndex, 0].ToString() + "', '" + lblcampana.Text + "','"+ GridView2.Rows[0].Cells[1].Text  + "','" + LBLSUPERV.Text + "','" + ddlEstado.SelectedValue + "')";
    }
}

Thanks for the help!!!

Ok, so this is one of the most classic setups in db land!

We have some parent records, and for each record, we need to display (and edit) child rows.

Now there are more UI choices for this then flavors of ice-cream.

And this suggests we need to "nest" the master records (say in a grid) to display of the child reocrds (our 2nd grid).

Well, it turns out that grids REALLY don't nest well.

So, for parent record(s), lets use a ListView - they work much better.

Ok, so we can fire up the wizards - build the LV, and THEN GO NUCLEAR weapons here and delete + blow out ALL the templates. And while we add this, delete the extra nested table. I count < 2 minutes of time.

So, we now have this simple LV.

    <asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
       <ItemTemplate>
          <tr>
            <td><asp:Button ID="cmdView" runat="server" Text="+" /></td>
            <td><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
            <td><asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' /></td>
            <td><asp:Label ID="ProvinceLabel" runat="server" Text='<%# Eval("Province") %>' /></td>
            <td><asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' /></td>
          </tr>

           </ItemTemplate>
       <LayoutTemplate>
        <table id="itemPlaceholderContainer" runat="server" class = "table table-hover" >
            <tr runat="server" style="">
                <th runat="server">View</th>
                <th runat="server">HotelName</th>
                <th runat="server">City</th>
                <th runat="server">Province</th>
                <th runat="server">Description</th>
            </tr>
            <tr id="itemPlaceholder" runat="server">
            </tr>
         </table>
       </LayoutTemplate>
    </asp:ListView>

 </div>

And our code to fill is this:

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

    void LoadMainGrid()
    {
        string strSQL = "SELECT * FROM tblHotels ORDER BY HotelName";
        ListView1.DataSource = MyRst(strSQL);
        ListView1.DataBind();
    }

And we now have this:

在此处输入图像描述

Ok, so now we need the child grid.

Then we MOVE this to be child grid into the above LV.

So, now we have this markup:

<tr>
<td colspan="5">
    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="ID" CssClass="table table-hover borderhide" style="display:none;width:97%;margin-left:2%"  >
        <Columns>
            <asp:TemplateField HeaderText="First Name">
                <ItemTemplate>
                    <asp:TextBox ID="FirstName" runat="server" Text='<%# Eval("FirstName") %>'  />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Last Name">
                <ItemTemplate>
                    <asp:TextBox ID="LastName" runat="server" Text='<%# Eval("LastName") %>'  />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:TextBox ID="City" runat="server" Text='<%# Eval("City") %>'  />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Start date">
                <ItemTemplate>
                    <asp:TextBox ID="dtStart" runat="server" Text='<%# Eval("dtStart", "{0:yyyy-MM-ddTHH:mm}") %>'  TextMode="DateTimeLocal" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="End date">
                <ItemTemplate>
                    <asp:TextBox ID="dtEnd" runat="server" Text='<%# Eval("dtEnd","{0:yyyy-MM-ddTHH:mm}") %>' TextMode="DateTimeLocal" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</td>

</ItemTemplate>

So we dropped in above right after the markup for the lv columns.

Now, all we have to do is wire up the the "+" button to expand:

That was the first row button in the LV

 <td><asp:Button ID="cmdView" runat="server" Text="+"  OnClick="cmdView_Click"/></td>

And the code is this:

    protected void cmdView_Click(object sender, EventArgs e)
    {
        Button cmd = (Button)sender;
        ListViewDataItem gVR = (ListViewDataItem)cmd.NamingContainer;
        GridView gChild = (GridView)gVR.FindControl("GridView2");   // pluck out the grid for this row

        if (gChild.Style["display"] == "normal")
        {
            // if grid is already display, then hide it, and exit
            gChild.Style["display"] = "none";
            return;
        }
        gChild.Style["display"] = "normal";
        int HotelPK = (int)ListView1.DataKeys[gVR.DataItemIndex]["ID"];

        // only re-load if never loaded
        if (gChild.Rows.Count == 0)
        {
            gChild.DataSource = MyRst("SELECT * from People where hotel_id = " + HotelPK);
            gChild.DataBind();
        }
    }

So, now we have this:

在此处输入图像描述

Ok, so now all we have to do is create a "save" button that saves any changes we made to this GV.

that is quite easy, and so we drop in a save button like this:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM