Solved

Add/Edit/Delete MySQL Rows (in C#)?

Posted on 2006-06-21
6
1,435 Views
Last Modified: 2011-04-14
I have a lame script that can connect to my database and get all the names, but I can't figure out how to do anything beyond that. I want to be able to add, edit, and delete rows. I know the SQL syntax to do it, but I don't know how to have ASP.Net (C#) do it. The following code will get all the names out of my database and display them. After I add, edit, or delete a row, I want to show the current database. I am thinking I just make this a function and then after the query, I call this function to show the results...is that right? How do I execute the SQL query?

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="MySql.Data.MySqlClient" %>
<%@ Page Language="C#" Debug="true" %>

<script runat="server">

      protected override void OnInit(EventArgs e)
      {
            base.OnInit(e);

          string ConnectString =
              ConfigurationSettings.AppSettings["connectString"];
          MySqlDataAdapter adapter = new MySqlDataAdapter
             ("select * from Names", ConnectString);
          DataSet ds = new DataSet ();
          adapter.Fill (ds);
          dgrAllNames.DataSource = ds;
          dgrAllNames.DataBind ();
      }
</script>

<html>
<head>
      <title>Displaying Records from MySQL 'Names' table</title>
      <style>
      body { font: 100% Verdana; }
      </style>
</head>
<body>

<p align="center">All records in the 'Names' table:</p>

<asp:DataGrid ID="dgrAllNames" HorizontalAlign="Center" CellPadding="3" Runat="server" />

</body>
</html>
0
Comment
Question by:HarryDuno16957
  • 2
6 Comments
 
LVL 15

Accepted Solution

by:
GavinMannion earned 500 total points
ID: 16957555
I am not 100% sure of the exact names but I think you will need

MySqlCommand myCommand = new MySqlCommand();
myCommand.ConnectionString = ConnectString;
myCommand.CommandText = "DELETE FROM Names";
myCommand.Open();
myCommand.ExecuteNonQuery();

Same idea for update and insert..
0
 
LVL 12

Expert Comment

by:deanvanrooyen
ID: 16959175
hi,

first is it asp.net 1.1 or 2.0? you are using the datagrid so i suspect 1.1...

check this out
http://www.codersource.net/asp_net_datagrid_part1_azam.html

what is required -  you need to add columns to the grid, and at least the edit column. bind the data to the grid. then you write an event handler that is connected to the update command from the edit column, to fire insert sql on the db...

another link to check
http://samples.gotdotnet.com/quickstart/aspplus/samples/webforms/ctrlref/webctrl/datagrid/doc_datagrid.aspx

this is an example of a basic grid with 2 table fields(id and name) and and edit column for edit and update current data - you can look up how to do insert new row and delete.

aspx page
///////////////////
    <asp:DataGrid ID="DataGrid1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" Height="4px" AutoGenerateColumns="False"
              OnCancelCommand="DataGrid1_Cancel"
              OnEditCommand="DataGrid1_Edit"
              OnUpdateCommand="DataGrid1_Update"  Width="617px"> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
              <EditItemStyle BackColor="#2461BF" HorizontalAlign="Left" ForeColor="White"  />
              <SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
              <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
              <AlternatingItemStyle BackColor="White" />
              <ItemStyle BackColor="#EFF3FB" />
              <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
              <columns>
                  <asp:TemplateColumn HeaderText="LastName">
                      <ItemTemplate>
                          <asp:Label ID="id" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "id") %>'></asp:Label>
                      </ItemTemplate>
                  </asp:TemplateColumn>
                  <asp:TemplateColumn HeaderText="FirstName">
                      <ItemTemplate>
                          <asp:Label ID="name" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "name") %>'></asp:Label>
                      </ItemTemplate>
                      <EditItemTemplate>
                          <asp:TextBox ID="nameedit" runat="server" Width="80" Text='<%# DataBinder.Eval(Container.DataItem, "name")%>' />
                      </EditItemTemplate>
                  </asp:TemplateColumn>
                  <asp:EditCommandColumn EditText="Edit"
                          CancelText="Cancel"
                          UpdateText="Update">
                          </asp:EditCommandColumn>
             
              </columns>
          </asp:DataGrid>
////////////////

code behind
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
           try
            {
                Bind();
            }
            catch (Exception er)
            {
             
            }
        }

 public void Bind()
 {  

        string select = "select * from names";
        DBConnectionStrings db = new DBConnectionStrings();

        MySqlConnection accessConnection = new MySqlConnection(db.MySqlConnectionString);
        MySqlCommand cmd = new MySqlCommand(select, accessConnection);
        MySqlDataAdapter da = new MySqlDataAdapter();
        da.SelectCommand = cmd;
        DataTable tableCalls = new DataTable();
        tableCalls.Locale = System.Globalization.CultureInfo.InvariantCulture;
        da.Fill(tableCalls);
        DataGrid1.DataSource = tableCalls.DefaultView;
        DataGrid1.DataBind();
}

    protected void DataGrid1_Cancel(object sender, DataGridCommandEventArgs e)
    {
         DataGrid1.EditItemIndex = -1;
         Bind();
    }

    protected void DataGrid1_Edit(object sender, DataGridCommandEventArgs e)
    {
        DataGrid1.EditItemIndex = e.Item.ItemIndex;
        Bind();
    }

    protected void DataGrid1_Update(object sender, DataGridCommandEventArgs e)
    {
        DBConnectionStrings myconstr = new DBConnectionStrings();
        MySqlConnection conn = new MySqlConnection(myconstr.MySqlConnectionString);
        string sql = "update names set name = ?name where id  = ?id"

        Label id = (Label)e.Item.FindControl("id");
        TextBox name= (TextBox)e.Item.FindControl("nameedit");

        MySqlCommand myCmd = new MySqlCommand(sql, conn);
        myCmd.Parameters.Add("?id", MySqlDbType.Int32).Value = Convert.ToInt32 (id.Text);
        myCmd.Parameters.Add("?name", MySqlDbType.Double).Value = name.Text;

        try
        {
            conn.Open();
            myCmd.ExecuteNonQuery();
            conn.Close();
           
        }
        catch(MySqlException me)
        {
        }
        DataGrid1.EditItemIndex = -1; //take out of editing mode
        Bind();
    }



0
 
LVL 12

Expert Comment

by:deanvanrooyen
ID: 17135615
hopefully the solution worked...
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video discusses moving either the default database or any database to a new volume.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now