Page view counter

Update/Edit/Delete records in a GridView

Last post 10-31-2008 3:22 PM by mckrecker. 8 replies.

Sort Posts:

  • Update/Edit/Delete records in a GridView

    10-31-2008, 7:36 AM
    • Loading...
    • mfreitas
    • Joined on 10-10-2008, 4:09 PM
    • Posts 7
    • Points 0

    Hi,

     I am trying to write some code to update/edit/delete records in a GridView but I am having problems. The GridView is populated through a stored procedure. Here is the code and the error I am getting. I have been doing searches over the net for the last two days and could not find an explanation that works. Can someone be so kind and explain me how can I write some code that will do just that?

    Store Procedure (GetAgendaHoje)
    SELECT CONVERT(VARCHAR(10), e.data_evento, 103) as Data, e.hora_evento Hora, c.nome Utilizador, e.local_evento Local, e.descricao Descrição, id_registo
    from customers c, registo e
    where e.data_evento = convert(char(10),getdate(),112)
    order by 1,2,
     

    -----

    <asp:GridView ID="dgAgenda" runat="server" AutoGenerateColumns="False"
    BorderColor="Black" BorderStyle="Solid"
    BorderWidth="2px" CellPadding="4" ForeColor="#333333"
    OnRowDataBound="dgAgenda_RowDataBound"
    datakeynames="id_registo"
    Width="714px" style="text-align: left" onrowupdated="dgAgenda_UpdateCommand">
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    <Columns>
    <asp:BoundField DataField="Data" HeaderText="Data" />
    <asp:BoundField DataField="Hora" HeaderText="Hora" />
    <asp:BoundField DataField="Utilizador" HeaderText="Utilizador" />
    <asp:BoundField DataField="Local" HeaderText="Local" />
    <asp:BoundField DataField="Descri‡ão" HeaderText="Descri‡ão" />
    <asp:BoundField DataField="id_registo" HeaderText="id_registo" ShowHeader="False" Visible="False"/>
    <asp:CommandField HeaderText="Edit" ShowEditButton="True" ShowHeader="True" />
    </Columns>
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="White" />
    </asp:GridView>

    -----

    private void inicializa()
    {
    SqlConnection conn = new SqlConnection(strLiga());
    SqlCommand cmd44 = new SqlCommand("GetAgendaHoje", conn);
    cmd44.CommandType =
    CommandType.StoredProcedure;
    conn.Open();
    SqlDataReader dr2 = cmd44.ExecuteReader();
    if (dr2.HasRows)
    {
    dgAgenda.DataSource = dr2;
    dgAgenda.DataBind();
    dr2.Close();
    }
    }

    public void dgAgenda_UpdateCommand(object sender, GridViewUpdateEventArgs e)
    {
    SqlConnection conn = new SqlConnection(strLiga());
    conn.Open();
    SqlCommand cmd2 = new SqlCommand("updateRegisto", conn);
    cmd2.CommandType =
    CommandType.StoredProcedure;
    cmd2.Parameters.Add(
    "@date", SqlDbType.DateTime).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
    cmd2.Parameters.Add(
    "@hora", SqlDbType.Time).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
    cmd2.Parameters.Add(
    "@util", SqlDbType.VarChar, 250).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
    cmd2.Parameters.Add(
    "@local", SqlDbType.VarChar, 250).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
    cmd2.Parameters.Add(
    "@desc", SqlDbType.VarChar, 250).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
    cmd2.Parameters.Add(
    "@id", SqlDbType.Int).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
    cmd2.ExecuteNonQuery();
    conn.Close();
    updateGrid();
    dgAgenda.EditIndex = -1;
    inicializa();
    }

    When I run the apps I get this error

    Compilation Error

    Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

    Compiler Error Message: CS0123: No overload for 'dgAgenda_UpdateCommand' matches delegate 'System.Web.UI.WebControls.GridViewUpdatedEventHandler'

     

  • Re: Update/Edit/Delete records in a GridView

    10-31-2008, 8:16 AM
    • Loading...
    • paindaasp
    • Joined on 12-19-2007, 12:47 PM
    • Exit 3
    • Posts 429
    • Points 2,474

    Here's my guess, for what it's worth.

    You are using onrowupdated="dgAgenda_UpdateCommand" with GridViewUpdateEventArgs e when onrowupdated should use GridViewUpdatedEventArgs so, try either changing GridViewUpdateEventArgs to GridViewUpdatedEventArgs or onrowupdated to onrowupdating.

    Hope this helps.

  • Re: Update/Edit/Delete records in a GridView

    10-31-2008, 8:38 AM
    • Loading...
    • mfreitas
    • Joined on 10-10-2008, 4:09 PM
    • Posts 7
    • Points 0

    Thanks that worked but now when I press the Edit button on the grid nothing happens, it wasn't supose to get the Update and Cancel buttons? any ideas? Here is the code:

    <asp:GridView ID="dgAgenda" runat="server" AutoGenerateColumns="False"
    BorderColor="Black" BorderStyle="Solid"
    BorderWidth="2px" CellPadding="4" ForeColor="#333333"
    OnRowDataBound="dgAgenda_RowDataBound"
    datakeynames="id_registo"
    Width="714px" style="text-align: left" onrowupdating="dgAgenda_UpdateCommand"
    onrowediting="editgrid_click">
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    <Columns>
    <asp:BoundField DataField="Data" HeaderText="Data" />
    <asp:BoundField DataField="Hora" HeaderText="Hora" />
    <asp:BoundField DataField="Utilizador" HeaderText="Utilizador" />
    <asp:BoundField DataField="Local" HeaderText="Local" />
    <asp:BoundField DataField="Descri‡ão" HeaderText="Descri‡ão" />
    <asp:BoundField DataField="id_registo" HeaderText="id_registo" ShowHeader="False" Visible="False"/>
    <asp:CommandField HeaderText="Edit" ShowEditButton="True" ShowHeader="True" />
    </Columns>
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="White" />
    </asp:GridView>

    protected void editgrid_click(object sender, GridViewEditEventArgs e)
    {
    dgAgenda.EditIndex = -1;
    inicializa();
    }

  • Re: Update/Edit/Delete records in a GridView

    10-31-2008, 9:28 AM
    • Loading...
    • paindaasp
    • Joined on 12-19-2007, 12:47 PM
    • Exit 3
    • Posts 429
    • Points 2,474

    In your posted code, I don't see anything that looks like it could cause what you are describing, so guess #2:

    something in updateGrid(); is goofing it up.

  • Re: Update/Edit/Delete records in a GridView

    10-31-2008, 9:50 AM
    • Loading...
    • mckrecker
    • Joined on 10-24-2008, 10:07 AM
    • Posts 170
    • Points 894

     The handler for the Edit button is editgrid_click, but in that handler all that happens is that the editindex is set to -1.  So, the user selects a row to edit -- EditIndex = row number -- and then the handler deselects it -- EditIndex = -1.  Is that your intent? Am I misunderstanding your issue?

    please mark as an answer if my reply helped
  • Re: Update/Edit/Delete records in a GridView

    10-31-2008, 11:13 AM
    • Loading...
    • mfreitas
    • Joined on 10-10-2008, 4:09 PM
    • Posts 7
    • Points 0

    You are right, I have changed the editgrid_click method. Let me try to explain what I need.

    When the form is first displayed I am running a stored procedure to get all the records for TODAYS date. On the form I have a calendar where the user can select a new date. When that happens I run the updategrid() to get the records for that particular day. But now the grid is not responding correctly. If I select a different day from the calendar and the press Edit strange things start to happen. Please check all the code behind

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

    {

    public partial class regista_evento : System.Web.UI.Page

    {

    public string LastColumn;
    protected void Page_Load(object sender, EventArgs e)

    {

    if (!Page.IsPostBack)

    {

    Session[
    "CustomerId"] = User.Identity.Name;
    Calendar1.SelectedDate =
    DateTime.Today;

    SqlConnection conn = new SqlConnection(strLiga());
    SqlCommand cmd4 = new SqlCommand("getNome", conn);

    // define store proc.

    cmd4.CommandType = CommandType.StoredProcedure;
    conn.Open();

    // Passa paremtro do primeiro PT na DropDownList

     

    cmd4.Parameters.Add(
    new SqlParameter("@cust", SqlDbType.Int));
    cmd4.Parameters.Add(
    new SqlParameter("@nome", SqlDbType.VarChar, 100, ParameterDirection.Output, false, 0, 100, "Novo Registo", DataRowVersion.Default, null));

    // carrega parametro

    cmd4.Parameters[0].Value = Session["CustomerId"];

    cmd4.ExecuteNonQuery();
    cmd4.UpdatedRowSource =
    UpdateRowSource.OutputParameters;
    string nome = cmd4.Parameters["@nome"].Value.ToString();

    Session["NomeUtilizador"] = nome;
    lblInfo.Text = nome;

    inicializa();

    LastColumn =
    "";

    }

    }

    private void updateGrid()

    {

    SqlConnection conn = new SqlConnection(strLiga());

    SqlCommand cmd45 = new SqlCommand("GetAgendaDiaSel", conn);

    cmd45.CommandType = CommandType.StoredProcedure;

    conn.Open();

    cmd45.Parameters.Add(
    new SqlParameter("@date", SqlDbType.DateTime));

    cmd45.Parameters[0].Value = Calendar1.SelectedDate;

    SqlDataReader dr1 = cmd45.ExecuteReader();if (dr1.HasRows)

    {

    dgAgenda.DataSource = dr1;

    dgAgenda.DataBind();

    dr1.Close();

    }

    }

    private void inicializa()

    {

    SqlConnection conn = new SqlConnection(strLiga());

    SqlCommand cmd44 = new SqlCommand("GetAgendaHoje", conn);

    cmd44.CommandType = CommandType.StoredProcedure;

    conn.Open();

    SqlDataReader dr2 = cmd44.ExecuteReader();if (dr2.HasRows)

    {

    dgAgenda.DataSource = dr2;

    dgAgenda.DataBind();

    dr2.Close();

    }

    }

    public void dgAgenda_RowDataBound(object sender, GridViewRowEventArgs e)

    {

    if (e.Row.RowType == DataControlRowType.DataRow)

    {

    string dup = e.Row.Cells[0].Text;if (LastColumn == dup)

    {

    e.Row.Cells[0].Text = "";

    e.Row.Cells[0].Style.Add("BORDER", "none");

    }

    if (LastColumn != dup)

    {

    LastColumn = e.Row.Cells[0].Text;

    e.Row.Cells[0].BackColor = System.Drawing.
    Color.Tomato;

    }

    }

    }

    string strLiga()

    {

    // Carrega liga‡ão … base de dados do web.config

    string connStr = ConfigurationSettings.AppSettings["connStr"];return connStr;

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

    DateTime dt = Convert.ToDateTime(dataText.Text);

    // cria instancia de comando e liga‡ão

    SqlConnection conn = new SqlConnection(strLiga());

    conn.Open();

    SqlCommand cmd22 = new SqlCommand("insertRegisto", conn);

    cmd22.CommandType = CommandType.StoredProcedure;

    cmd22.Parameters.Add(new SqlParameter("@customer", SqlDbType.Int));

    cmd22.Parameters.Add(new SqlParameter("@data", SqlDbType.DateTime));

    cmd22.Parameters.Add(new SqlParameter("@hora", SqlDbType.Time));

    cmd22.Parameters.Add(new SqlParameter("@local", SqlDbType.VarChar,250));

    cmd22.Parameters.Add(new SqlParameter("@desc", SqlDbType.VarChar,250));

     

    string strCustIdd = (string)Session["CustomerId"];

    string hora = ddlHora.SelectedValue.ToString();

    int custIdd = Convert.ToInt32(strCustIdd);

     

    // carrega parametro

    cmd22.Parameters[0].Value = custIdd;

    cmd22.Parameters[1].Value = dt;

    cmd22.Parameters[2].Value = hora;

    cmd22.Parameters[3].Value = localText.Text;

    cmd22.Parameters[4].Value = descText.Text;

     

    cmd22.ExecuteNonQuery();

    conn.Close();

    updateGrid();

    dataText.Text =
    "";

    ddlHora.SelectedIndex = -1;

    localText.Text =
    "";descText.Text = "";

    }

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)

    {

    //Label1.Text = "escolhi o dia" + Calendar1.SelectedDate;

    updateGrid();

    }

    // Delete Command Definition

    public void gridedit_DeleteCommand(object sender, GridViewRowEventArgs e)

    {

    // cria instancia de comando e liga‡ão

    SqlConnection conn = new SqlConnection(strLiga());

    conn.Open();

    SqlCommand cmd3 = new SqlCommand("deleteRegisto", conn);

    cmd3.CommandType = CommandType.StoredProcedure;

    cmd3.Parameters.Add("@id", SqlDbType.Int).Value = ((TextBox)e.Row.Cells[5].Controls[0]).Text;

    cmd3.ExecuteNonQuery();

    cmd3.ExecuteNonQuery();

    cmd3.Connection.Close();

    dgAgenda.EditIndex = -1;

    inicializa();

    }

    protected void editgrid_click(object sender, GridViewEditEventArgs e)

    {

    dgAgenda.EditIndex = e.NewEditIndex;

    dgAgenda.DataBind();

    }

    public void dgAgenda_UpdateCommand(object sender, GridViewUpdateEventArgs e)

    {

    // cria instancia de comando e liga‡ão

    SqlConnection conn = new SqlConnection(strLiga());

    conn.Open();

    SqlCommand cmd2 = new SqlCommand("updateRegisto", conn);

    cmd2.CommandType = CommandType.StoredProcedure;

    cmd2.Parameters.Add("@date", SqlDbType.DateTime).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[0].Controls[0]).Text;

    cmd2.Parameters.Add("@hora", SqlDbType.Time).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[1].Controls[0]).Text;

    cmd2.Parameters.Add("@util", SqlDbType.VarChar, 250).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[2].Controls[0]).Text;

    cmd2.Parameters.Add("@local", SqlDbType.VarChar, 250).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[3].Controls[0]).Text;

    cmd2.Parameters.Add("@desc", SqlDbType.VarChar, 250).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[4].Controls[0]).Text;cmd2.Parameters.Add("@id", SqlDbType.Int).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[5].Controls[0]).Text;

    cmd2.ExecuteNonQuery();

    conn.Close();

    updateGrid();

    dgAgenda.EditIndex = -1;

    inicializa();

    }

    protected void dgAgenda_CancelEdit(object sender, GridViewCancelEditEventArgs e)

    {

    dgAgenda.EditIndex = -1;

    inicializa();

    }

    //protected void gridedit_DeleteCommand(object sender, GridViewDeletedEventArgs e)

    //{

    // // cria instancia de comando e liga‡ão

    // SqlConnection conn = new SqlConnection(strLiga());

    // conn.Open();

    // SqlCommand cmd3 = new SqlCommand("deleteRegisto", conn);

    // cmd3.CommandType = CommandType.StoredProcedure;

    // int U_ID = (int)dgAgenda.DataKeys[(int)e.RowIndex];

    // cmd3.Parameters.Add("@id", SqlDbType.Int).Value = ((TextBox)dgAgenda.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString();

    // cmd3.ExecuteNonQuery();

    // cmd3.ExecuteNonQuery();

    // cmd3.Connection.Close();

    // dgAgenda.EditIndex = -1;

    // inicializa();

    //}

    }

    }

     

  • Re: Update/Edit/Delete records in a GridView

    10-31-2008, 11:40 AM
    • Loading...
    • mckrecker
    • Joined on 10-24-2008, 10:07 AM
    • Posts 170
    • Points 894

     I read through the code a couple of times and I don't see anything in particular that would be an issue.  It looks like this would correctly update the dgAgenda after the selected date changes.  Are you sure that it's posting back when the date changes? What are the strange things that are happening?

    please mark as an answer if my reply helped
  • Re: Update/Edit/Delete records in a GridView

    10-31-2008, 12:26 PM
    • Loading...
    • mfreitas
    • Joined on 10-10-2008, 4:09 PM
    • Posts 7
    • Points 0

    Inittilay the grid appears correctly but if I select a diff date the grid dissapears. If I select de initial date the grid reappears with a row selected for update. It's really odd. 

  • Re: Update/Edit/Delete records in a GridView

    10-31-2008, 3:22 PM
    • Loading...
    • mckrecker
    • Joined on 10-24-2008, 10:07 AM
    • Posts 170
    • Points 894

     It sounds to me like there is no data for the second date you select.  The intial date has data and data appears, the second has no data so nothing appears.  You go back to the first date and data appears.

    So, are you absolutely certain that there is data associated with teh second date? If so, try looking for something in how the data is acquired, something in the stored procedure or in the parameter you pass.  Don't know what it might be.

    Personally, my next step would be to run this through a debugger step by step so I could see what's happening.  Like I said, it sounds like there's no data for that second date.

    please mark as an answer if my reply helped
Page 1 of 1 (9 items)