How can you insert records using a MySql databound GridView.

How can you insert records using a MySql databound GridView? I am trying to figure out how to make it so i can insert records into the database using the GridView. I know one way is to make footer templates with text boxes for each field and add a button at the end that causes the insert on button click.

But im not sure how to make that way work really so looking for anyone who knows how to make it work. Thanks!

Im using visual studio.net 2005, the website uses asp.net 2.0 and C#, and uses a MySql 5.1 database

FigleAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MrAgileCommented:
Hi There,

I have pasted a snippet of code below. It allows you to insert a row using a gridview. It's using a sql datasource and you will need to modify the fields in order to get it to work.

Just ask if you any help with it.

Sean
gridview -----
 
          <asp:GridView ID="grvCampaign" Width="100%" DataSourceID="srcCampaign" AutoGenerateColumns="False"
                    AllowPaging="True" EmptyDataText="There are no records to display" ShowFooter="True"
                    AllowSorting="True" DataKeyNames="CampaignID" PageSize="50" runat="server" AutoGenerateDeleteButton="True"
                    OnRowCommand="grvCampaign_RowCommand">
                    <Columns>
                        <asp:CommandField ShowEditButton="true" />
              
                          <asp:TemplateField ConvertEmptyStringToNull="true" HeaderText="Offer ID"
                            SortExpression="CampaignID">
                            <EditItemTemplate>
                                <asp:Label ID="lblCampaignID" runat="server" Text='<%# Bind("CampaignID") %>'></asp:Label>
                            </EditItemTemplate>
                            <ItemTemplate>
                                 <asp:Label ID="lblCampaignID" runat="server" Text='<%# Bind("CampaignID") %>'></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
 
                            </FooterTemplate>
                           
                        </asp:TemplateField>   
                            
                     
                      
                        <asp:TemplateField HeaderText="Offer Name">
                            <EditItemTemplate>
                                <asp:RequiredFieldValidator ValidationGroup="update" ID="rfvtxtName" runat="server"
                                    ErrorMessage="*" ControlToValidate="txtName" SetFocusOnError="true"></asp:RequiredFieldValidator>
                                <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("CampaignName") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("CampaignName") %>'></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:RequiredFieldValidator ID="rfvtxtName" runat="server" ErrorMessage="*" ControlToValidate="txtName"
                                    SetFocusOnError="true" ValidationGroup="insert"></asp:RequiredFieldValidator>
                                <asp:TextBox ID="txtName" Width="100px" runat="server" Text='<%# Bind("CampaignName") %>'></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
                       
 
                        <asp:TemplateField HeaderText="Add Content" SortExpression="Activate">
                            
                            <ItemTemplate>
                               <asp:Button ID="btnActivate" runat="server" CommandArgument='<%# Bind("CampaignType") %>' CommandName='<%# Bind("CampaignID") %>' Text="Add Content"
                                    CausesValidation="false" OnCommand="Activate_Click"  />
                            </ItemTemplate>
                             <FooterTemplate>
                                <asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Add Offer"
                                    CausesValidation="true"  ValidationGroup="insert" />
                            </FooterTemplate>
                        </asp:TemplateField>
 
                    </Columns>
                </asp:GridView>
 
 
---- code for command
 
 
 
 protected void grvCampaign_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
           
 
                if (e.CommandName.Equals("Insert"))
                {
//do stuff here
                 }
 
}

Open in new window

0
FigleAuthor Commented:
Thanks im  trying it out now
0
FigleAuthor Commented:
It gives me this error when i try to load it in a broswer
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 
 
Compiler Error Message: CS0117: 'ASP.test_aspx' does not contain a definition for 'Activate_Click'
 
Source Error:
 
 
 
Line 47:                             
Line 48:                             <ItemTemplate>
Line 49:                                <asp:Button ID="btnActivate" runat="server" CommandArgument='<%# Eval("LastName") %>' CommandName='<%# Bind("Badge") %>' Text="Add Content"
Line 50:                                     CausesValidation="false" OnCommand="Activate_Click"  />
Line 51:                             </ItemTemplate>
 

Open in new window

0
Newly released Acronis True Image 2019

In announcing the release of the 15th Anniversary Edition of Acronis True Image 2019, the company revealed that its artificial intelligence-based anti-ransomware technology – stopped more than 200,000 ransomware attacks on 150,000 customers last year.

MrAgileCommented:
Hi There,

do you have the following line OnRowCommand="Activate_Click"> in your gridview?
0
FigleAuthor Commented:
When i do the insert its not sending the values to the database, it in debug it shows it has the values to be inserted right until the insert command happens then it loses them.



<asp:SqlDataSource ID="lccr" runat="server" 
        ProviderName="System.Data.Odbc" 
        ConnectionString="Driver={MySQL ODBC 5.1 Driver};server=columbia;database=lccr;user=jacob.powers;pwd=Smurfs88;option=3" 
        InsertCommand="INSERT INTO employeestatus(Badge, `First Name`) VALUES (Badge,'`First Name`')" 
        
        SelectCommand="SELECT Badge, `First Name`, `Last Name` FROM employeestatus">
        
        <InsertParameters>
            <asp:Parameter Name="Badge" Type="String" />
            <asp:Parameter Name="First Name" Type="String" />
            </InsertParameters>
            
        </asp:SqlDataSource>
 
 
public partial class TEST : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    protected void grvCampaign_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
        
 
        if (e.CommandName.Equals("Insert"))
        {
 
TextBox TestNumTextBox = grvCampaign.FooterRow.FindControl("TestNumTextBox") as TextBox;
        TextBox TestNameTextBox = grvCampaign.FooterRow.FindControl("TestNameTextBox") as TextBox;
            //do stuff here
            lccr.InsertParameters["Badge"].DefaultValue = TestNumTextBox.Text;
            lccr.InsertParameters["First Name"].DefaultValue = TestNameTextBox.Text;
            lccr.Insert();
        }
 
    }
 
}

Open in new window

0
FigleAuthor Commented:
badge is the primary key field and first is another column in the table
0
MrAgileCommented:
Hi there,

if you're using the parameters you need to put the @ symbol. (i'm not familiar wuth mysql). I would also recommend not having any spaces in the names either.

1. rename the columns without spaces (last_name)
2. change the insert statement to have the @ symbol before the name itself


Let me know how it goes.
 InsertCommand="INSERT INTO employeestatus(Badge, First_Name) VALUES (@Badge,@First_Name)" 
        
        SelectCommand="SELECT Badge, `First Name`, `Last Name` FROM employeestatus">
        
        <InsertParameters>
            <asp:Parameter Name="Badge" Type="String" />
            <asp:Parameter Name="First_Name" Type="String" />
            </InsertParameters>
            
        </asp:SqlDataSource>

Open in new window

0
FigleAuthor Commented:
@ does not work with MySql
0
MrAgileCommented:
try VALUES(?, ?)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.