Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2006-06-21
6
Medium Priority
?
1,459 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
6 Comments
 
LVL 15

Accepted Solution

by:
GavinMannion earned 2000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

715 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