[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

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

Posted on 2006-06-21
6
Medium Priority
?
1,469 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
3 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

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Question has a verified solution.

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

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
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…
Is your organization moving toward a cloud and mobile-first environment? In this transition, your IT department will encounter many challenges, such as navigating how to: Deploy new applications and services to a growing team Accommodate employee…
Hi, this video explains a free download that you can incorporate into your Access databases, or use stand-alone for contact management. Contacts -- Names, Addresses, Phone Numbers, eMail Addresses, Websites, Lists, Projects, Notes, Attachments…
Suggested Courses
Course of the Month7 days, 14 hours left to enroll

607 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