Solved

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

Posted on 2006-06-21
6
1,437 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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

786 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