如何从datagrivew将数据加载到文本框

时间:2015-03-28 05:37:32

标签: c# asp.net datagridview

我有两个带有datagridview的文本框。我正在插入和编辑。所以我想要的是能够从datagridview点击用户并将数据加载到文本框中,以便我可以编辑和保存。

我该怎么做?

我的插入代码

protected void btndrivers_Click(object sender, EventArgs e)
{
    try
    {
           Drivers _da = new Drivers();
        int _driversId = 0;
        int SaveMode = 0;

        OConnection = new SqlConnection(_ConnectionString);
        oCommand = new SqlCommand("SELECT Drivername from TB_DRIVER WHERE Drivername = @Drivername AND DriverID <> @DriverID", OConnection);
        oCommand.Parameters.AddWithValue("@Drivername", txtdrivername.Text.Trim());
        oCommand.Parameters.AddWithValue("@DriverID", _driversId.ToString());
        OConnection.Open();
        SqlDataReader oReader = oCommand.ExecuteReader();
        if (oReader.HasRows)
        {
            lblexist.Visible = true;
            lblexist.Text = "Driver name " + txtdrivername.Text.Trim() + " already exist! ";
        }
        else
        {
            switch (SaveMode)
            {
                case 1:
                    {
                     bool _var = _da.AddnewDrivers
                         (_driversId, 
                         txtdrivername.Text, 
                         txtdriversurname.Text
                         );                 
                    }
                    break;

                case 2:
                    {
                        bool _var = _da.UpdateDrivers
                            (_driversId, 
                            txtdrivername.Text, 
                            txtdriversurname.Text
                            );
                    }
                    break;
            }

            if (SaveMode == 2)
            {
                lblInfor.Text = "CONFIRMATION: New drivers details saved successfully.....";
                LoadDrivers();
            }

            imgInfo.Visible = true;
            lblInfor.Visible = true;
            lblInfor.Text = "CONFIRMATION: New drivers details saved successfully.....";
            LoadDrivers();

        }
        txtdrivername.Text = "";
        txtdriversurname.Text = "";

    }
    catch (Exception ex)
    {
    }
} 


protected void GrdDrivers_SelectedIndexChanged(object sender, EventArgs e)
{
    LoadDrivers();
    {
        if (_driversId != 0)
        {
            SaveMode = 2;
            Odataset = _da.GetDriversDetails(_driversId);
            if (Odataset.Tables[0].Rows.Count > 0)
            {
                txtdrivername.Text = Odataset.Tables[0].Rows[0][1].ToString();
                txtdriversurname.Text = Odataset.Tables[0].Rows[0][1].ToString();
            }
        }
        else
        {
            lblErr.Text = "Please select records and continue";
        }
    }
}

  <asp:GridView ID="GrdDrivers" runat="server" AutoGenerateColumns="False" 
                BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" 
                CellPadding="4" CellSpacing="3" ForeColor="Black" 
                Width="100%" onrowcommand="GrdDrivers_RowCommand" 
                onselectedindexchanged="GrdDrivers_SelectedIndexChanged" > 
                <Columns>
                    <asp:TemplateField HeaderText="">
                        <ItemTemplate>
                            <asp:LinkButton ID="lbtSno" runat="server" CausesValidation="False" 
                                CommandArgument='<%# Eval("Drivername")%>' CommandName="StrucID" ForeColor="red">Edit</asp:LinkButton>

                        </ItemTemplate>
                        <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="15%" />
                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                    </asp:TemplateField>
                    <asp:BoundField DataField="Drivername" HeaderStyle-Width="30%" 
                        HeaderText="Driver Name" ItemStyle-HorizontalAlign="Center" 
                        ItemStyle-VerticalAlign="Middle">
                    <HeaderStyle Width="30%" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                    </asp:BoundField>
                    <asp:BoundField DataField="DriverSurname" HeaderStyle-Width="30%" 
                        HeaderText="Driver Surname" ItemStyle-HorizontalAlign="Center" 
                        ItemStyle-VerticalAlign="Middle">
                    <HeaderStyle Width="30%" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                    </asp:BoundField>
                </Columns>
                <RowStyle BackColor="White" />
                <FooterStyle BackColor="#CCCCCC" />
                <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#4B6C9E" Font-Bold="True" ForeColor="White" />
                <AlternatingRowStyle BackColor="#E3EAEB" />
            </asp:GridView>

3 个答案:

答案 0 :(得分:0)

在datagridview mouseclick / cellcontent上点击'events'提供填写文本框的代码。

  textBox1.Text = datagridview.Cells[1].Value.ToString();

其中“1”是单元格索引。

答案 1 :(得分:0)

试试这个..

protected void btnSave_Click(object sender, EventArgs e)
    {
        if (btnSave.Text == "Save")
        {
            int ID = Convert.ToInt32(txtdriverId.Text);
            int name= Convert.ToInt32(txtdrivername.Text);
            string sqlstr = "insert into TB_DRIVER(driverId,drivername) values(" + ID + "," + name + ")";
            SqlCommand cmd = new SqlCommand(sqlstr, con);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();
            BindGrid();
            btnSave.Text = "Save";

        }
        if (btnSave.Text == "Update")
        {
            int ID = Convert.ToInt32(driverId.Text);
            int name= Convert.ToInt32(txtdrivername.Text);
            sqlstr = "update TB_DRIVER set driverId=" + ID + ", drivername=" + name + " where driverId=" + ID;
            SqlCommand cmd = new SqlCommand(sqlstr, con);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();
            BindGrid();
            btnSave.Text = "Save";
        }
    }
    protected void GrdDrivers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            int ID = Convert.ToInt32(e.CommandArgument);
            ViewState["ID"] = ID;
            string str = "select * from TB_DRIVER where driverId = '" + ID + "'";
            SqlCommand cmd = new SqlCommand(str, con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                txtdriverId.Text = dr[0].ToString();
                txtdrivername.Text = dr[1].ToString();
            }
            con.Close();
            btnSave.Text = "Update";
        }
        BindGrid();
    }
    protected void GrdDrivers_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    protected void GrdDrivers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    public void BindGrid()
    {
        string sqlstr = "Select * from TB_DRIVER";
        SqlDataAdapter da = new SqlDataAdapter(sqlstr, con);
        DataTable ds = new DataTable();
        da.Fill(ds);
        GrdDrivers.DataSource = ds;
        GrdDrivers.DataBind();
    }
<asp:GridView ID="GrdDrivers" runat="server" AutoGenerateColumns="false" HorizontalAlign="Center"
            OnRowCommand="GrdDrivers_RowCommand" OnRowDeleting="GrdDrivers_RowDeleting" OnRowEditing="GrdDrivers_RowEditing">
            <Columns>
                <asp:TemplateField HeaderText="Driver ID">
                    <ItemTemplate>
                        <asp:Label ID="lblDriverID" runat="server" Text='<%# Bind("DriverID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Driver Name">
                    <ItemTemplate>
                        <asp:Label ID="lblDrivername" runat="server" Text='<%# Bind("Drivername") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" Text="Edit" CommandArgument='<%# Eval("DriverID") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

答案 2 :(得分:0)

在gridview按钮内:

   <asp:LinkButton runat="server" ID="lnkEdit" OnClick="lnkEdit_Click" Text="Edit"></asp:LinkButton>

在cs页面上:

  protected void lnkEdit_Click(object sender, EventArgs e)
    {
        GridViewRow row = (GridViewRow)((LinkButton)sender).NamingContainer;

        txt1.Text = row.Cells[0].Text;
        txt2.Text = row.Cells[1].Text;
    }