C# - 将值从一个页面传输到动态gridview的文本框

时间:2016-03-18 15:47:39

标签: c# asp.net gridview

这是我的aspx页面,描述了一个动态网格视图:

  <asp:gridview ID="Gridview1"  runat="server"  ShowFooter="True"  
                         AutoGenerateColumns="False"  
                         OnRowCreated="Gridview1_RowCreated" style="margin-left: 13px; margin-right: 6px; margin-top: 12px;" Width="1035px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">  
<Columns>  
    <asp:BoundField DataField="RowNumber" HeaderText="#" />  
    <asp:TemplateField HeaderText="Disease">  
        <ItemTemplate>  
            <asp:Button ID="Icd" runat="server" Text="ICD 10" Height="23px" Width="69px" OnClick="Icd_Click" />
            <asp:TextBox ID="TextBox1" runat="server" Height="23px" Width="301px" MaxLength="100"></asp:TextBox>  
        </ItemTemplate>  
        <ItemStyle CssClass="gvCell"></ItemStyle>
    </asp:TemplateField>  
    <asp:TemplateField HeaderText="Year">  
        <ItemTemplate>  
            <asp:TextBox ID="TextBox2"  runat="server" Height="23px" Width="95px" MaxLength="4"></asp:TextBox>  
        </ItemTemplate>  
        <ItemStyle CssClass="gvCell"></ItemStyle>
    </asp:TemplateField>  
    <asp:TemplateField  HeaderText="Stuation">  
        <ItemStyle CssClass="gvCell"></ItemStyle>
        <ItemTemplate>  
            <asp:DropDownList ID="DropDownList1" runat="server"  
                                      AppendDataBoundItems="true" Height="23px">  
                <asp:ListItem Value="-1">--Επιλέξτε--</asp:ListItem>  
            </asp:DropDownList>  
        </ItemTemplate>  
    </asp:TemplateField>  
    <asp:TemplateField HeaderText="Therapy"> 
         <ItemStyle CssClass="gvCell"></ItemStyle>
       <ItemTemplate>  
            <asp:TextBox ID="TextBox3"  runat="server" Height="23px" Width="223px" MaxLength="100"></asp:TextBox>  
        </ItemTemplate>  
        <FooterStyle HorizontalAlign="Right" />  
        <FooterTemplate>  
            <asp:Button ID="ButtonAdd" runat="server"   
                                 Text="+Add new row"   
                                 onclick="ButtonAdd_Click" />  
        </FooterTemplate>  
    </asp:TemplateField>  
    <asp:TemplateField>  
        <ItemStyle CssClass="gvCell"></ItemStyle>
        <ItemTemplate>  
            <asp:LinkButton ID="LinkButton1" runat="server"   
                                    onclick="LinkButton1_Click">Delete row</asp:LinkButton>  
        </ItemTemplate>  
    </asp:TemplateField>  
</Columns>  
                <FooterStyle BackColor="#006466" ForeColor="Black" />
                <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
                <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#F7F7F7" />
                <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
                <SortedDescendingCellStyle BackColor="#E5E5E5" />
                <SortedDescendingHeaderStyle BackColor="#242121" />

这是aspx.cs代码:

    private ArrayList GetDummyData()                             
    {
        ArrayList arr = new ArrayList();

        arr.Add(new ListItem("Πάσχει", "1"));
        arr.Add(new ListItem("Έπασχε", "2"));

        return arr;
    }

    private void FillDropDownList(DropDownList ddl)                         
    {
        ArrayList arr = GetDummyData();

        foreach (ListItem item in arr)
        {
            ddl.Items.Add(item);
        }
    }

    private void SetInitialRow()
    {

        DataTable dt = new DataTable();
        DataRow dr = null;

        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for TextBox value   
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value   
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for DropDownList selected item   
        dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for TextBox value  

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;   
        dr["Column2"] = string.Empty;
        dr["Column4"] = string.Empty;
        dt.Rows.Add(dr);

        //Store the DataTable in ViewState for future reference   
        ViewState["CurrentTable"] = dt;

        //Bind the Gridview   
        Gridview1.DataSource = dt;
        Gridview1.DataBind();

        //After binding the gridview, we can then extract and fill the DropDownList with Data   
        DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList1");
        FillDropDownList(ddl1);                               
    }

    private void AddNewRowToGrid()
    {

        if (ViewState["CurrentTable"] != null)
        {

            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;

            if (dtCurrentTable.Rows.Count > 0)
            {
                drCurrentRow = dtCurrentTable.NewRow();
                drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;

                //add new row to DataTable   
                dtCurrentTable.Rows.Add(drCurrentRow);
                //Store the current data to ViewState for future reference   

                ViewState["CurrentTable"] = dtCurrentTable;


                for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
                {

                    //extract the TextBox values   

                    TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");  
                    TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox3");

                    dtCurrentTable.Rows[i]["Column1"] = box1.Text;
                    dtCurrentTable.Rows[i]["Column2"] = box2.Text;
                    dtCurrentTable.Rows[i]["Column4"] = box3.Text;

                    //extract the DropDownList Selected Items   

                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList1");     

                    // Update the DataRow with the DDL Selected Items   

                    dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text;                         
                }

                //Rebind the Grid with the current data to reflect changes   
                Gridview1.DataSource = dtCurrentTable;
                Gridview1.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");

        }
        //Set Previous Data on Postbacks   
        SetPreviousData();
    }

    private void SetPreviousData()
    {

        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {

            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
                    TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("TextBox3");


                    //Fill the DropDownList with Data   
                    FillDropDownList(ddl1);                          

                    if (i < dt.Rows.Count - 1)
                    {

                        //Assign the value from DataTable to the TextBox   
                        box1.Text = dt.Rows[i]["Column1"].ToString();
                        box2.Text = dt.Rows[i]["Column2"].ToString();
                        //Set the Previous Selected Items on Each DropDownList  on Postbacks   
                        ddl1.ClearSelection();
                        ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;
                        box3.Text = dt.Rows[i]["Column4"].ToString();
                    }

                    rowIndex++;
                }
            }
        }
    }


    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }

    protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1");
            if (lb != null)
            {
                if (dt.Rows.Count > 1)
                {
                    if (e.Row.RowIndex == dt.Rows.Count - 1)
                    {
                        lb.Visible = false;
                    }
                }
                else
                {
                    lb.Visible = false;
                }
            }
        }
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        LinkButton lb = (LinkButton)sender;
        GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
        int rowID = gvRow.RowIndex;
        if (ViewState["CurrentTable"] != null)
        {

            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 1)
            {
                if (gvRow.RowIndex < dt.Rows.Count - 1)
                {
                    //Remove the Selected Row data and reset row number  
                    dt.Rows.Remove(dt.Rows[rowID]);
                    ResetRowID(dt);
                }
            }

            //Store the current data in ViewState for future reference  
            ViewState["CurrentTable"] = dt;

            //Re bind the GridView for the updated data  
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }

        //Set Previous Data on Postbacks  
        SetPreviousData();
    }

    private void ResetRowID(DataTable dt)
    {
        int rowNumber = 1;
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                row[0] = rowNumber;
                rowNumber++;
            }
        }
    }  

    private string GetConnectionString()
    {
        return ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
    }

    private void InsertRecords(StringCollection sc)
    {
        if (Session["pa_id"] != null)
        {
            StringBuilder sb = new StringBuilder(string.Empty);
            string[] splitItems = null;
            const string sqlStatement = "INSERT INTO P_deasease (Date,P_Id,Nosos,Situ,Year_d,Therapy) VALUES";
            int id = Convert.ToInt32(Session["pa_id"]);
            foreach (string item in sc)
            {
                if (item.Contains(","))
                {
                    splitItems = item.Split(",".ToCharArray());
                    sb.AppendFormat("{0}(@Date, @p_id ,N'{1}',N'{2}',N'{3}',N'{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
                }
            }

            using (SqlConnection connection = new SqlConnection(GetConnectionString()))
            {
                connection.Open();


                using (SqlCommand cmd = new SqlCommand(sb.ToString(), connection))
                {
                    cmd.Parameters.AddWithValue("@p_id", id);
                    cmd.Parameters.AddWithValue("@Date", DateTime.Now.ToShortDateString());
                    cmd.CommandType = CommandType.Text;
                    cmd.ExecuteNonQuery();

                }
            }


            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Text = "Success!";
        }
        else
        {
            lblid1.Visible = true;
        }
    }

    protected void BtnSave_Click(object sender, EventArgs e)
    {
        int rowIndex = 0;
        StringCollection sc = new StringCollection();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the values  
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox3");

                    //add them to the collections with a comma "," as the delimited values  
                    sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, ddl1.SelectedItem.Text, box2.Text, box3.Text));
                    rowIndex++;
                }
                //Call the method for executing inserts  
                InsertRecords(sc);
            }
        }
    }

正如您在第1栏中看到的那样,有一个按钮和一个文本框。 单击该按钮时,会出现一个弹出窗口,其中包含“在数据库中搜索”机制。

enter image description here

因此,当在弹出窗口的gridview中选择一个值时,我想将其传输到相应的文本框。

enter image description here

如何将值传输到相应的文本框?作为初学者,我在这方面遇到了很大的困难。任何帮助将不胜感激

0 个答案:

没有答案