Hej
Jeg er begyndt at "lege" lidt med asp.net og c# men er gået lidt i stå.
Jeg kan ikke rigtig finde ud af hvordan jeg connecter til en mysql database og læser data fra den.
Jeg har prøvet at google lidt, og har fået lavet denne kode.
<%@ Page language="c#" Codebehind="MySqlDataGrid.aspx.cs" AutoEventWireup="false" Inherits="Speech.MySqlDataGrid" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
</HEAD>
<body>
<P>
<form runat="server">
<TABLE id="Table1" height="176" cellSpacing="1" cellPadding="1" width="344" border="0">
<TR>
<TD bgColor="#cccc99"></TD>
</TR>
<TR>
<TD bgColor="gainsboro">
<TABLE id="HtmlTable1" style="BORDER-COLLAPSE: collapse" cellSpacing="0" cellPadding="3"
rules="all" align="center" bgColor="gainsboro" border="1" runat="server">
<TR style="BACKGROUND-COLOR: #f7f7f7">
<TD bgColor="gainsboro">fornavn</TD>
<TD bgColor="gainsboro">efternavn</TD>
<TD bgColor="gainsboro"> </TD>
</TR>
<TR>
<TD width="100">
<asp:TextBox id="TextBox3" runat="server"></asp:TextBox></TD>
<TD width="100">
<asp:TextBox id="TextBox4" runat="server"></asp:TextBox></TD>
<TD>
<asp:Button id="btn_add" runat="server" Text="Add" BorderStyle="None"></asp:Button></TD>
</TR>
</TABLE>
</TD>
</TR>
<TR>
<TD>
<asp:DataGrid id="DataGrid1" Runat="server" DataKeyField="ID" AutoGenerateColumns="False" EditItemStyle-BackColor="#F7F7F7"
HeaderStyle-BackColor="#F7F7F7" CellPadding="3" HorizontalAlign="Center">
<FooterStyle BackColor="PaleGoldenrod"></FooterStyle>
<SelectedItemStyle BackColor="Control"></SelectedItemStyle>
<EditItemStyle BackColor="#F7F7F7"></EditItemStyle>
<ItemStyle BackColor="White"></ItemStyle>
<HeaderStyle BackColor="DarkKhaki"></HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderText="ID">
<HeaderStyle Width="30px"></HeaderStyle>
<ItemTemplate>
<asp:Literal ID="Label" Text='<%# DataBinder.Eval(Container.DataItem, "ID") %>' Runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Name">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" Text='<%# DataBinder.Eval(Container.DataItem, "name") %>' CssClass="stdInput" Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Address">
<HeaderStyle Width="100px"></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "address") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Textbox2" Text='<%# DataBinder.Eval(Container.DataItem, "address") %>' CssClass="stdInput" Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit"></asp:EditCommandColumn>
<asp:ButtonColumn Text="Delete" CommandName="Delete"></asp:ButtonColumn>
</Columns>
</asp:DataGrid></TD>
</TR>
<TR>
<TD bgColor="gainsboro">
<TABLE id="HtmlTable2" style="BORDER-COLLAPSE: collapse" cellSpacing="0" cellPadding="3"
rules="all" align="center" bgColor="#ffcc99" border="1" runat="server" Visible="False">
<TR>
<TD width="234" bgColor="#cccc33">Errors</TD>
</TR>
<TR>
<TD>
<asp:RequiredFieldValidator id="Requiredfieldvalidator1" Runat="server" ErrorMessage="*First Name* is a required field"
EnableClientScript="False" Display="None" ControlToValidate="Textbox3" ForeColor="RosyBrown"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator id="Requiredfieldvalidator2" Runat="server" ErrorMessage="*Last Name* is a required field"
EnableClientScript="False" Display="None" ControlToValidate="Textbox4" ForeColor="RosyBrown"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator id="Regularexpressionvalidator1" Runat="server" ErrorMessage="*First Name* contains illegal values"
EnableClientScript="False" Display="None" ControlToValidate="Textbox3" ForeColor="RosyBrown" ValidationExpression="[\w\s]{1,255}"></asp:RegularExpressionValidator>
<asp:RegularExpressionValidator id="Regularexpressionvalidator2" Runat="server" ErrorMessage="*Last Name* contains illegal values"
EnableClientScript="False" Display="None" ControlToValidate="Textbox4" ForeColor="RosyBrown" ValidationExpression="[\w\s]{1,255}"></asp:RegularExpressionValidator>
<asp:ValidationSummary id="ValidationSummary1" Runat="server" ForeColor="RosyBrown" ShowSummary="True"
DisplayMode="List"></asp:ValidationSummary></TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</form>
</P>
</body>
</HTML>
Min MySqlDataGrid.aspx.cs fil ser sådan her ud
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.Odbc;
namespace Speech
{
/// <summary>
/// Summary description for MySqlDataGrid.
/// </summary>
public class MySqlDataGrid : System.Web.UI.Page
{
protected System.Web.UI.WebControls.ValidationSummary ValidationSummary1;
protected System.Web.UI.WebControls.RegularExpressionValidator Regularexpressionvalidator2;
protected System.Web.UI.WebControls.RegularExpressionValidator Regularexpressionvalidator1;
protected System.Web.UI.WebControls.RequiredFieldValidator Requiredfieldvalidator2;
protected System.Web.UI.WebControls.RequiredFieldValidator Requiredfieldvalidator1;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Web.UI.WebControls.Button btn_add;
protected System.Web.UI.HtmlControls.HtmlTable HtmlTable1;
protected System.Web.UI.HtmlControls.HtmlTable HtmlTable2;
private const string ConnStr = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=cms;uid=root;pwd=ijujkuo8;option=3";
string strSort;
string strerrorMsg;
protected System.Web.UI.WebControls.TextBox TextBox3;
protected System.Web.UI.WebControls.TextBox TextBox4;
string strscriptString;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
{
if (strSort == "")
{
strSort = "IntegerValue";
}
BindDataGrid();
}
}
private void BindDataGrid()
{
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("SELECT * FROM user", con))
{
con.Open();
DataGrid1.DataSource = cmd.ExecuteReader(
CommandBehavior.CloseConnection |
CommandBehavior.SingleResult);
DataGrid1.DataBind();
}
}
private void InsertInfo()
{
if(CheckIsAddNameValid())
{
HtmlTable2.Visible = false;
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("INSERT INTO user(firstname, lastname) VALUES (?,?)", con))
{
cmd.Parameters.Add("@name", OdbcType.VarChar, 255).Value = TextBox3.Text.Trim();
cmd. Parameters.Add("@address", OdbcType.VarChar, 255).Value = TextBox4.Text.Trim();
con.Open();
cmd.ExecuteNonQuery();
BindDataGrid();
}
}
}
private void UpdateInfo(int id, string name, string address)
{
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("UPDATE user SET firstname = ?, lastname = ? WHERE ID = ?", con))
{
cmd.Parameters.Add("@name", OdbcType.VarChar, 255).Value = name;
cmd.Parameters.Add("@address", OdbcType.VarChar, 255).Value = address;
cmd.Parameters.Add("@ID", OdbcType.Int).Value = id;
con.Open();
cmd.ExecuteNonQuery();
}
}
private void DeleteInfo(int id)
{
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("DELETE FROM user WHERE ID = ?", con))
{
cmd.Parameters.Add("@ID", OdbcType.Int).Value = id;
con.Open();
cmd.ExecuteNonQuery();
}
}
private bool CheckIsAddNameValid()
{
HtmlTable2.Visible = true;
Requiredfieldvalidator1.Validate();
Requiredfieldvalidator2.Validate();
Regularexpressionvalidator1.Validate();
Regularexpressionvalidator2.Validate();
return (Requiredfieldvalidator1.IsValid &&
Requiredfieldvalidator2.IsValid &&
Regularexpressionvalidator1.IsValid &&
Regularexpressionvalidator2.IsValid);
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btn_add.Click += new System.EventHandler(this.btn_add_Click);
this.DataGrid1.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_CancelCommand);
this.DataGrid1.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_EditCommand);
this.DataGrid1.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.DataGrid1_SortCommand);
this.DataGrid1.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand);
this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_DeleteCommand);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
}
private void btn_add_Click(object sender, System.EventArgs e)
{
InsertInfo();
}
private void Textbox4_TextChanged(object sender, System.EventArgs e)
{
}
private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
BindDataGrid();
}
private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
try
{
int cUsrID ;
string strName;
string strAddress;
Literal ltID;
TextBox txtTempName;
TextBox txtTempAddress;
ltID = (System.Web.UI.WebControls.Literal ) e.Item.Cells[0].FindControl("Label");
cUsrID = Convert.ToInt32 (ltID.Text);
txtTempName = (System.Web.UI.WebControls.TextBox)e.Item.Cells[1].FindControl("TextBox1");
strName = txtTempName.Text;
txtTempAddress = (System.Web.UI.WebControls.TextBox) e.Item.Cells[2].FindControl("Textbox2");
strAddress = txtTempAddress.Text;
UpdateInfo(cUsrID, strName, strAddress);
DataGrid1.EditItemIndex = -1;
BindDataGrid();
}
catch(Exception ex)
{
strerrorMsg = ex.Message.Replace("'", @"""");
strscriptString = "<script language = Javascript>";
strscriptString += "window.status = '" + strerrorMsg + "';";
strscriptString += "</script>";
RegisterStartupScript("clientScript", strscriptString);
}
}
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
try
{
int cID;
Literal ltID = null;
string ss = string.Empty;
ltID = (System.Web.UI.WebControls.Literal ) e.Item.Cells[0].FindControl("Label");
cID = Convert.ToInt32 (ltID.Text);
DeleteInfo(cID);
BindDataGrid();
}
catch(Exception ex)
{
strerrorMsg = ex.Message.Replace("'", @"""");
strscriptString = "<script language = Javascript>";
strscriptString += "window.status = '" + strerrorMsg + "';";
strscriptString += "</script>";
RegisterStartupScript("clientScript", strscriptString);
}
}
private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = -1;
BindDataGrid();
}
}
}
Men jeg får følgende fejl når jeg prøver at åbne den.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not load type 'Speech.MySqlDataGrid'.
Source Error:
Line 1: <%@ Page language="c#" Codebehind="MySqlDataGrid.aspx.cs" AutoEventWireup="false" Inherits="Speech.MySqlDataGrid" %>
Line 2: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
Line 3: <HTML>
Source File: /MySqlDataGrid.aspx Line: 1