Hi . I want to know how pass the data from the datagrid to textbox through query string with only the ID of the selected row being passed as query i.e when I select a particular row all the attributes of that row should be displayed on the textboxes of another page :
Below is d code for the first page that has d datagrid :

 <asp:DataGrid ID="DataGrid1" AutoGenerateColumns="False" runat="server" DataKeyField="Empid"
    OnDeleteCommand="DataGrid1_DeleteCommand" OnCancelCommand ="DataGrid1_CancelCommand" OnUpdateCommand ="DataGrid1_UpdateCommand"  OnEditCommand ="DataGrid1_EditCommand" BackColor="#DEBA84" BorderColor="#DEBA84"
            BorderWidth="1px" CellPadding="3" BorderStyle="None" CellSpacing="2" Height="296px"
            Width="488px">
            <Columns>
                <asp:BoundColumn DataField="Empid" HeaderText="Empid" Visible="false"></asp:BoundColumn>
                <asp:BoundColumn DataField="EmpName" HeaderText="EmpName"></asp:BoundColumn>
                <asp:BoundColumn DataField="Address" HeaderText="Address"></asp:BoundColumn>
                <asp:BoundColumn DataField="Salary" HeaderText="Salary"></asp:BoundColumn>
                <asp:BoundColumn DataField="DeptName" HeaderText="DeptName"></asp:BoundColumn>
                <asp:TemplateColumn HeaderText="Edit" >
                    <ItemTemplate>
                        <asp:Image runat="server" Width="50" Height="40" ImageUrl="~/Images/images.jpg" />

<asp:HyperLink NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"Empid","~/Default.aspx?Empid={0}" ) %>' Text="Edit" id = "HyperLink2" runat="server"></asp:HyperLink>
                    </ItemTemplate>
               </asp:TemplateColumn>

              <asp:ButtonColumn CommandName="Edit" Text="Edit"  ></asp:ButtonColumn>
                <asp:TemplateColumn HeaderText="Delete">
                    <ItemTemplate>
                        <asp:Image runat="server" Width="50" Height="40" ImageUrl="~/Images/cross.jpg" />
                    </ItemTemplate>
                </asp:TemplateColumn>
                <asp:ButtonColumn CommandName="Delete" Text="Delete"></asp:ButtonColumn>
              <asp:ButtonColumn CommandName="AddNew" Text="Insert"></asp:ButtonColumn>
            </Columns>

        </asp:DataGrid>

And the code for the second page wherein the textboxes r there is as follows :

<table border="1">
            <tr>
                <td>
                    Name:
                </td>
                <td class="style1">

                    <asp:TextBox ID="txtname_e" runat="server" Width="167px" Text='<%# DataBinder.Eval(Container, "DataItem.EmpName") %>' ></asp:TextBox>

                </td>
            </tr>
            <tr>
                <td>
                    Address:
                </td>
                <td class="style1"> 

        <asp:TextBox ID="txtadd_e" runat="server" TextMode="MultiLine" Width="176px" Text='<%# DataBinder.Eval(Container, "DataItem.Address") %>'></asp:TextBox>

                <br />
                </td>
            </tr>
            <tr>
                <td class="style2" >
                Salary :
                </td>
                 <td class="style3"> 

                   <asp:TextBox ID="textbox3" runat="server" Width="176px" Text='<%# DataBinder.Eval(Container, "DataItem.Salary") %>'></asp:TextBox>


                </td>  
            </tr>
            <tr>
                <td colspan= "1" >
                    Department name :
                </td>

               <td> 
                    <asp:DropDownList runat="server" ID="DropDownList1" Height="31px" 
                        Width="179px" style="margin-bottom: 5px" >
                       <asp:ListItem> </asp:ListItem>

                    </asp:DropDownList>

                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
                    <br />
                    <br />
                    &nbsp;&nbsp;
                    </td>
                    </tr> 
                    <tr>
                    <td colspan= 2 align= center> 
                   <asp:Button ID="btnupdate" runat="server" CommandName="Update" Text="Update" onclick="btnupdate_Click" /> 
                     &nbsp;&nbsp;&nbsp;&nbsp;  

                   <asp:Button ID="Button2" runat="server" CommandName="Cancel" Text="Cancel" onclick="Button2_Click" /> 
                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                     <asp:Button ID="btnadd" runat="server" OnClick="btnadd_Click" Text="Add New Record" />
                   </td> 

                   </tr>  

        </table>

and the code behind file :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
 string strid = Request.QueryString["Empid"];

            if (!Page.IsPostBack)
            {

              FillDeptDropDownList();
    }


} 

    protected void btnadd_Click(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void Button2_Click(object sender, EventArgs e)
    {

    }


    protected void FillDeptDropDownList()
    {
        String strConnString = ConfigurationManager.ConnectionStrings["Company"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlCommand cmd = new SqlCommand("Select * from Department", con);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        DropDownList1.DataSource = dt;
        DropDownList1.DataTextField = "DeptName";
        DropDownList1.DataValueField = "DeptID";
        DropDownList1.DataBind();
        DropDownList1.Items.Insert(0, "Select department name:");



    }


    protected void btnupdate_Click(object sender, EventArgs e)
    {
        if (btnadd.Text == "Update Record")
        {
            btnadd.Text = "Cancel";



        }
        else
        {
            btnadd.Text = "Add New Record";

        }


    }
} 

Recommended Answers

All 12 Replies

I can see that you are grabbing the EmpID query string value in the Page Load event but I don't see where you are using it.

Yes , I have just passed the EmpID in the querystring but i want to know how it can be used so that data from the datagrid be populated in the textboxes in the second page .

You could grab the data when the page loads, maybe before you populate your DropDownList. The following demonstrates this but will need tweaking to suit your needs. It also assumes only one row will be retrieved as you are using an ID to limit the results:

string selectStatement = "SELECT YourColumns FROM YourTable WHERE EmployeeID=@EmployeeID";

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

    using (SqlCommand command = new SqlCommand(selectStatement, connection))
    {
        command.Parameters.AddWithValue("@ClientID", strid);

        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            YourTextBox.Text = reader["ColumnName"].ToString();
        }
    }
}

HTH

Hi , I tried using the code . it works . Now d next thing wat i want is that to edit data in datagrid and then click on update . I hv written d following code but after clicking on update , it doesnt show any changes .

protected void DataGrid1_EditCommand(object source, DataGridCommandEventArgs e)
    {
        DataGrid1.EditItemIndex = e.Item.ItemIndex;
        FillDataGrid();

    }

    protected void DataGrid1_UpdateCommand(object source, DataGridCommandEventArgs e)
    {
        int Empid = Convert.ToInt32(DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
        TextBox txtname_e = (TextBox)DataGrid1.Items[e.Item.ItemIndex].Cells[1].FindControl("txtname_e");
        TextBox txtadd_e = (TextBox)DataGrid1.Items[e.Item.ItemIndex].Cells[2].FindControl("txtadd_e");
        TextBox textbox3 = (TextBox)DataGrid1.Items[e.Item.ItemIndex].Cells[3].FindControl("textbox3");
        string dbcon = ConfigurationManager.ConnectionStrings["Company"].ConnectionString;
        SqlConnection con = new SqlConnection(dbcon);
        con.Open();
        SqlCommand cmd = new SqlCommand("Update Employee set EmpName='" + txtname_e.Text + "',Address='" + txtadd_e.Text + "' where Empid=" + Empid, con);

        //DataGrid1.DataKeys[e.Item.ItemIndex].ToString()
        int rows = cmd.ExecuteNonQuery();
        if (rows > 0)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Updated", "<script>alert('Updated Successfully')</script>");

            con.Close();
            DataGrid1.EditItemIndex = -1;
            FillDataGrid();
            }
            }

I want to know whether i need to put some code in update button ie btnupdate_Click ..

Does the above do anything? Do you get an alert to say that rows were affected?

Once i click on edit , data from the grid gets populated in the textbox and m able to make changes , but the update is not happening .

But i dont get any alert saying rows were affected .

Have you tried debugging and stepping through your code to see what it is doing?

Yes , but it doesnt get into the DataGrid1_UpdateCommand event d editCommand event executes well not the Updatecommand .

Hi , i used the foll code in the btnupdate_click :

 protected void btnupdate_Click(object sender, EventArgs e)
    {
        int strid = Convert.ToInt32(Request.QueryString["Empid"]);

        string cmdUpdate = "Update Employee set EmpName= test  , Address='" + txtadd_e.Text + "', Salary='" + textbox3.Text + "' where Empid=" + strid + " ";
        string dbcon = ConfigurationManager.ConnectionStrings["Company"].ConnectionString;
        SqlConnection con = new SqlConnection(dbcon);
        con.Open();
        SqlCommand cmd = new SqlCommand(cmdUpdate, con);
        cmd.ExecuteNonQuery();
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Updated", "<script>alert (Updated Successfully')</script>");
        con.Close();
    }

I was nt getting the data updated .. and it was showing same old data . I tried debugging the code . it gets executed but not getting updated.

Hi.. I am able to update data now .. i needed the code for inserting new data into the datagrid. i hv created a button in the main page , what code to be written in the addbutton .Please help .

Hi

To add data you would use an INSERT statement, something like:

string cmdInsert = "INSERT INTO Employee (EmpName, Address, Salary) VALUES ('" & empNameValue & "', '" & addressValue & "', '" & salaryValue & "')"

And then use the same code to execute the query against your database.

One other thing. I would recommend that you use parameterised queries instead of supplying the values directly into the query string to avoid SQL Injection attacks. So, the code would be a little different for both the update and insert statements:

string cmdInsert = "INSERT INTO Employee (EmpName, Address, Salary) VALUES (@EmpName, @Address, @Salary)"

string dbcon = ConfigurationManager.ConnectionStrings["Company"].ConnectionString;
SqlConnection con = new SqlConnection(dbcon);
con.Open();
SqlCommand cmd = new SqlCommand(cmdUpdate, con);

//Add the parameter values
cmd.Parameters.AddWithValue("@EmpName", empNameValue)
cmd.Parameters.AddWithValue("@Address", addressValue)
cmd.Parameters.AddWithValue("@Salary", SalaryValue)

cmd.ExecuteNonQuery();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.