Solved

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

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

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

Suggested Solutions

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…

730 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