HI, micah
Here I have created sample code that will help you.
HTML
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtMessage" runat="server" />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />
<asp:DataList ID="dlMessage" runat="server">
<HeaderTemplate>
<table>
<tr>
<th>
Message
</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblMessage" Text='<%#Eval("Message")%>' runat="server" />
<asp:Label ID="lblTime" Text='<%#Eval("MessageDate") %>' runat="server" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="lblRecord" Visible="false" runat="server" />
</div>
</form>
C#
private string Constr = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetMessage();
}
}
private void GetMessage()
{
using (SqlConnection con = new SqlConnection(Constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM MessageTable", con))
{
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
dlMessage.DataSource = dt;
dlMessage.DataBind();
lblRecord.Visible = false;
}
else
{
this.lblRecord.Visible = true;
this.lblRecord.Text = "No Record found";
}
}
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(Constr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO MessageTable Values(@Message,@MessageDate)", con);
cmd.Parameters.AddWithValue("@Message", txtMessage.Text);
cmd.Parameters.AddWithValue("@MessageDate", DateTime.Now);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.GetMessage();
}
}
SQL
CREATE TABLE MessageTable
(MessageId INT IDENTITY CONSTRAINT Pk_MID PRIMARY KEY NOT NULL,
Message VARCHAR(500) NOT NULL,
MessageDate DATETIME NOT NULL
);
I hope this code help you out.