Using a SQL Server Stored Procedure in Visual Studio - c#

My Experience & What I'm Using
So I'm just starting off with a very basic web application in ASP.NET to gain a little more familiarity with SQL Server Management Studios and Visual Studios 2010. Normally, I use MySQL, PHP, and Sublime Text Editor 2. I'm not very experienced with C# and implementing a database in Visual Studios. So I'm trying to use a stored procedure from SQL Server Management Studios and implement it in Visual Studios 2010.
The Issue
So here's my problem: I'm trying to create a basic webpage that links to a SQL Server and be able to add, delete, search and display all records from the database. Now I've written my own code based on what I thought was correct for add/delete and nothing happens when I click the buttons. So I'm sure you can see where my frustration derives from. I'm not sure if the issue is in my C# coding or in my SQL coding.
I'd like to focus on just getting my add/delete buttons to work and then to figure out the logic to display all files. I'd like to be able to click a button and then have it show all files instead of just displaying a grid. My database is called FirstApp.
Here's what's in my web.config file:
<add name="FirstApp" connectionString="Data Source=PCNAME\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True"
providerName="System.Data.SqlClient" />
Now this is what's in my Default.aspx.cs file:
*CORRECT CODE NOW!*
namespace FirstApp
{
public partial class _Default : System.Web.UI.Page
{
public string CommandArgument { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
private void MessageBox(string msg)
{
Label lbl = new Label();
lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
Page.Controls.Add(lbl);
}
//Add a new company to the database
protected void add_Click(object sender, EventArgs e)
{
SqlDataReader rdr = null;
string connectionString = null;
SqlConnection cnn;
connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("dbo.Add_Company", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#companyname", companyname.Text);
cmd.Parameters.AddWithValue("#companyphone", companyphone.Text);
cmd.Parameters.AddWithValue("#companyid", companyid.Text);
cmd.Parameters.AddWithValue("#companytype", companytype.Text);
rdr = cmd.ExecuteReader();
}
finally
{
//Close the connections
if (cnn != null)
{
cnn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
//Delete a company from the database
protected void delete_Click(object sender, EventArgs e)
{
SqlDataReader rdr = null;
SqlConnection cnn;
string connectionString = null;
connectionString = "Data Source=ITXDK29M91\\SQLEXPRESS;Initial Catalog=FirstApp;Integrated Security=True";
cnn = new SqlConnection(connectionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("dbo.deleteCo", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", SqlDbType.Int);
rdr = cmd.ExecuteReader();
}
finally
{
//Close the connections
if (cnn != null)
{
cnn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
protected void Search_Click(object sender, EventArgs e)
{
}
protected void Getall_Click(object sender, EventArgs e)
{
}
}
}
This is what's in my Source Code in Default.aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2>Ready for an Adventure? Let's get started!
</h2> <hr />This is where you can enter information about your company.
<br />
<form method="post" action="">
Company Name:<br />
<asp:TextBox ID="companyname" runat="server"></asp:TextBox>
<br />
Company Phone Number:<br />
<asp:TextBox ID="companyphone" runat="server"></asp:TextBox>
<br />
Company Tax ID Number:
<br />
<asp:TextBox ID="companyid" runat="server"></asp:TextBox>
<br />
Type of business: <br />
<asp:TextBox ID="companytype" runat="server"></asp:TextBox>
<br />
<asp:Button ID="add" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="add_Click" Text="Submit" Width="128px" />
</form> <hr />
Want to delete your company information?<br />
Enter in the Company ID Number:
<br />
<asp:TextBox ID="PrimaryKey" runat="server" Width="120px"></asp:TextBox>
<br />
<asp:Button ID="delete" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="delete_Click" Text="Delete Info" Width="119px" />
<br />
<hr />
Looking for similar companies?
<br />
(Ex: Retail, Designer, Restaurant, etc.)
<br />
Enter the type of company:
<br />
<asp:TextBox ID="scompanyid" runat="server" Width="120px"></asp:TextBox>
<br />
<asp:Button ID="Search" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="Search_Click" Text="Start Searching!" Width="119px" />
<br />
<hr />
Want to see all the companies that we work with? <br />
Click the button below!
<br />
<asp:Button ID="Getall" runat="server" BackColor="DeepSkyBlue"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CssClass="submitButton" Font-Names="Palatino Linotype" ForeColor="White"
onclick="Getall_Click" Text="Get all records!" Width="119px" />
<br />
<br />
</asp:Content>
UPDATE: I've updated the code to display the correct code. The add button works but my delete button is not. I'm still trying to figure that one out.

You're not actually opening a connection or executing your SQL commands. Generally, the way you execute a simple command is:
using (var conn = new SqlConnection(connectionString))
{
using (var comm = conn.CreateCommand())
{
conn.Open();
comm.CommandText = "SOME SQL HERE";
// command type, parameters, etc.
//pick one of the following
comm.ExecuteNonQuery();
int value = (int)comm.ExecuteScalar();
SqlDataReader reader = comm.ExecuteReader();
}
}

You need to actually execute the command. There are four types of execution (depending on the type of results you'll be expecting from your query statement)
ExecuteReader - Rows and columns returned (e.g. Normal select queries)
ExecuteNonquery - No results expected. (e.g. Deleting a record)
ExecuteScalar - Single value (e.g. Count, Max, etc..)
ExecuteXMLReader - For XML stuff
Something like this for the add
cmd.ExecuteNonquery();
Even before worrying about executing the command though, you always need an open connection through which you execute commands and you need to link your command to it:
SqlConnection cn = new SqlConnection(connStr);
cn.Command = cmd;
cn.Open();
<your command/parameter code here>
cmd.ExecuteNonquery();
And don't forget to put stuff back the way you found it:
cmd.Close();
cn.Close();
There are other suggestions I'd make--like making the phone number varchar since you're not going to do arithmetic on it as a number--but this is not your real question here and now.
Best wishes!
FYI: Side topic: Whenever you begin to use commands to return results, you will not need a "new" for your SqlDataReaders because commands executed with ExecuteReader create and return an SqlDataReader object. This means you can just do this
//This next line not needed
//dr = new SqlDataReader()
SqlDataReader dr = cmd.ExecuteReader();

It looks like you aren't executing your SQL statements. Try creating a method that does the below then call that method from your delete button click event.
public static void DeleteSomething()
{
using (var conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("usp_proc_delete", conn.CreateCommand()))
{
conn.Open()
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PrimaryKey", SqlDbType.Int);
cmd.ExecuteNonQuery();
}
}
}

Related

How do I post a message to a message board page that just contains a list of messages posted from users ASP.NET WebForm

I have just a simple message page which consists of From: Text: and a Submit button, then I have another page, which contains nothing, it's my "Message Board" the most recent posted message goes on top of the board, both are aspx pages with master page.
I have a SQL DB, I'm already assuming there will be a table with From: Message:(with varchar i think), but what i don't understand how it will get inserted into the messageboard page in a most recent to oldest list fashion.
Message.aspx - From: Text: Submit
MessageBoard.aspx - just a div , messages submitted will appear here in a drop down list
I want it to be super simple no cool features, only "Submit the message" -> "Appears on MessageBoard.aspx to everyone",
and that's it
Ok, there are seveal moving parts.
Assuming you have SQL server running. Assuming you have a valid conneciton?
Ok, then on the post a new message page, you have this markup:
<h3>Post a message</h3>
<h4>enter your name</h4>
<asp:TextBox ID="txtName" runat="server" Width="250px"></asp:TextBox>
<br />
<h4>Enter your message</h4>
<asp:TextBox ID="txtMsg" runat="server" Height="185px" Width="520px"
TextMode="MultiLine" Font-Size="Large" style="border-radius:20px;border:solid 2px"
></asp:TextBox>
<br />
<br />
<asp:Button ID="cmdNewMessage" runat="server" Text="Post Message" CssClass="btn"
OnClick="cmdNewMessage_Click" />
And code behind looks like this:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdNewMessage_Click(object sender, EventArgs e)
{
string strSQL =
#"INSERT INTO tblMessages (UName, Message, MessageDate)
VALUES (#UName, #Message, #MessageDate)";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
cmdSQL.Parameters.Add("#UName", SqlDbType.NVarChar).Value = txtName.Text;
cmdSQL.Parameters.Add("#Message",SqlDbType.NVarChar).Value = txtMsg.Text;
cmdSQL.Parameters.Add("#MessageDate", SqlDbType.NVarChar).Value = DateTime.Now;
cmdSQL.ExecuteNonQuery();
}
}
Response.Redirect("MessageBoard.aspx");
}
So, it looks like this:
when you hit post message, we jump to this page, and markup:
<asp:Button ID="cmdPost" runat="server"
Text="Post a new message"
CssClass="btn" OnClick="cmdPost_Click" />
<br />
<br />
<h2>Messages</h2>
<asp:GridView ID="GridView1" runat="server" Width="50%"
AutoGenerateColumns="False" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="UName" HeaderText="Posted by" />
<asp:BoundField DataField="MessageDate" HeaderText="At" ItemStyle-Width="180px" />
<asp:TemplateField HeaderText="Message" >
<ItemTemplate>
<asp:Textbox ID="txtMsg" runat="server" TextMode="MultiLine" Width="100%"
Text='<%# Eval("Message") %>'
Height='<%# (Regex.Matches(Eval("Message").ToString() , System.Environment.NewLine).Count + 1) * 30 %>'
>
</asp:Textbox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And code is:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT * FROM tblMessages ORDER BY MessageDate DESC";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
}
}
protected void cmdPost_Click(object sender, EventArgs e)
{
Response.Redirect("NewMessage.aspx");
}
And we now see/have this:
You don't explain what you mean by "what i don't understand how it will get inserted into the messageboard page in a most recent to oldest list fashion", so I can only guess.
When a new message is posted, you insert it into the database, including a DateTime column. Your message list page then just grabs the latest nn messages, ordered by newest first.
I'm assuming that you know how to do that. If not, do some reading about Entity Framework Core, as that provides a very good way of handling databases.
So, in princple, your question is no more complex than that. However, there are many variations on this, such as having the message list updated in real time, for which you should use SignalR, but without more specific explanation of what you want, it's hard to make any suggestions.

ASP.NET - Unable to insert data into database

I know that the connection string is not the problem because I can read data from the database fine but I cannot figure out why I cannot insert data into the database.
.aspx file
<div class="column one-second">
<asp:TextBox placeholder="Your name" type="text" name="name" id="namelbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one-second">
<asp:TextBox placeholder="location" type="text" name="location" id="LocationLbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
<asp:TextBox placeholder="Body" type="text" name="text" id="TextLBL" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
<asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload>
<asp:Label ID="lblmessage" runat="server" />
</div>
<div class="column one">
<asp:Button id="submit" Text="Submit" runat="server" OnClick="submit_Click"> </asp:Button>
</div>
C# function
protected void submit_Click(object sender, EventArgs e)
{
Console.WriteLine("BUTTON CLICKED");
string constr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO blo(Title, post, location) VALUES (#Title, #post, #location)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
string title = namelbl.Text;
Console.WriteLine(title);
cmd.Parameters.AddWithValue("Title", title);
string post = TextLBL.Text;
cmd.Parameters.AddWithValue("post", post);
string location = LocationLbl.Text;
cmd.Parameters.AddWithValue("location", location);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Your query was not able to work as you mistype the parameter name in your .AddWithValue().
cmd.Parameters.AddWithValue("Title", title);
cmd.Parameters.AddWithValue("post", post);
cmd.Parameters.AddWithValue("location", location);
The correct way should be:
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("#post", post);
cmd.Parameters.AddWithValue("#location", location);
RECOMMENDATIONS
1. It is recommended not to use `.AddWithValue()` as the concern mentioned in this [article](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/). Please ensure that you need to pass the value with **exact datatype and length** that matches the respective table column in the `SqlParameter`.
cmd.Parameters.Add("#Param", <<MySqlDbType>>, <<Length>>).Value = value;
As you apply using block for MySqlConnection, MySqlCommand, you don't have to manually call con.Close() as these IDisposable objects will dispose the resources & connection automatically as mentioned in this article.
(Optional) Add try catch block and get value from ExecuteNonQuery() for verifying the record is inserted into the database and exception handling.
Exception handling will be useful in debugging and handling the exception hit during the execution. At the same time, you can provide a meaningful error message to notify the users.
ExecuteNonQuery() able to return the value indicate
The number of rows affected.
Hence, this will also be useful to return a useful message to notify whether the record is successfully inserted/updated into the database or not.
In the end, your code should be:
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO blo(Title, post, location) VALUES (#Title, #Post, #Location)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
string title = namelbl.Text;
Console.WriteLine(title);
cmd.Parameters.AddWithValue("#Title", title);
string post = TextLBL.Text;
cmd.Parameters.AddWithValue("#Post", post);
string location = LocationLbl.Text;
cmd.Parameters.AddWithValue("#Location", location);
con.Open();
var recordAffected = (int)cmd.ExecuteNonQuery();
if (recordAffected > 0)
{
// Record successfully inserted case
}
else
{
// Record fail inserted case
}
}
}
}
catch (Exception ex)
{
// Handling exception
}
Edited:
Much appreciated and credited to the comment provided by #BradleyGrainger, I had 'strikethrough' recommendation 1 as the concerns mentioned in Can We Stop Using .AddWithValue() are handled by MySql.
Start Using AddWithValue
The primary reason that AddWithValue is OK to use is that MySQL’s text protocol is not typed in a way that matters for client-side type inference.

Code Not Preventing Duplicate E-mail Addresses in Database

The code I have is allowing duplicate e-mails to be added to the database. I added a line of code before allowing entry into the database to prevent duplicate e-mail addresses to be added, however with this code I am still getting duplicate e-mails. I have provided both the form code in asp.net & the c# code. Please help.
Originally I was getting an error & I debugged the code in VS & realized that I actually had the wrong specification for the email entry, that has been corrected. In the VS debugger I see values for TextBox1.Text & TextBox2.Text, i also see the e-mail address passing through the string query = the issue however is that even if the e-mail is already in the database, it still gets added again. Any improvements to fix this issue with my code? Is my logic wrong perhaps?
c# code:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwind"].ToString();
con.Open();
string query = "SELECT COUNT(ID) FROM Table1 WHERE pEmail= '" + TextBox2.Text +"'";
OleDbCommand cmd = new OleDbCommand(query, con);
var count = cmd.ExecuteNonQuery();
if (count > 0)
{
Label1.Text = "email is already in use";
}
else {
cmd.CommandText = "insert into[Table1](pName, pEmail)values(#nm,#em)";
cmd.Parameters.AddWithValue("#nm", TextBox1.Text);
cmd.Parameters.AddWithValue("#em", TextBox2.Text);
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a>0)
{
Label1.Text = "Inserted Sucessfully!";
}
}
}
}
Form Code:
<form id="form1" runat="server">
<div style="height: 138px">
Enter Name:<asp:TextBox ID="TextBox1" runat="server" style="margin-left: 12px"></asp:TextBox>
<asp:RequiredFieldValidator
id="reqName"
ControlToValidate="TextBox1"
Style="color:Red"
ErrorMessage="Please enter your name!"
runat="server" />
<br />
Enter Email:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator
id="ValidEmail"
ControlToValidate="TextBox2"
Style="color:Red"
ValidationExpression="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
ErrorMessage="Invalid Email Entry"
runat="server" />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
You should use ExecuteScalar instead of ExecuteNonQuery to get the row count
Original:
var count = cmd.ExecuteNonQuery();
Suggest to change:
var count = cmd.ExecuteScalar();
Refer to https://stackoverflow.com/a/4269651/1050927
The ExecuteNonQuery Method returns the number of row(s) affected by either an INSERT, an UPDATE or a DELETE. This method is to be used to perform DML (data manipulation language) statements as stated previously.
The ExecuteScalar Method will return a single value in the first row, first column from a SELECT statement. This method is to be used when you expect only one value from the query to be returned.
Use ExecuteScalar and Convert the result to int. I also recommend you to change the sql query concatenation to parameters, and if you are using ASP.NET Validators, you must check the property IsValid of the page as it will tell you if the controls has passed validation (remember that users can disable javascript and post the form).
protected void Button1_Click(object sender, EventArgs e)
{
if (IsValid)
{
using (var con = new OleDbConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwind"].ToString();
con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(ID) FROM Table1 WHERE pEmail= #em";
cmd.Parameters.AddWithValue("#em", TextBox2.Text);
int count = Convert.ToInt32(cmd.ExecutScalar());
if (count > 0)
{
Label1.Text = "email is already in use";
}
else
{
cmd.CommandText = "insert into[Table1](pName, pEmail)values(#nm, #em)";
cmd.Parameters.AddWithValue("#nm", TextBox1.Text);
// not need to add #em parameter, it was added previously
int insertedRows = cmd.ExecuteNonQuery();
if (insertedRows > 0)
{
Label1.Text = "Inserted Sucessfully!";
}
}
}
}
}
}

Save the data in database

Here I am trying to save the data in data base. Whatever data user enters it has to save in database and it has to save in page it self also. when user opens page that data has to display.
Code for aspx page
<asp:Label runat="server" ID="lblCnct" Text="Contact Number" AssociatedControlID="txtCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtCnct" CssClass="form-control" />
<asp:Label runat="server" ID="lblAltCnct" Text="Alternative Contact Number" AssociatedControlID="txtAltCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtAltCnct" CssClass="form-control" />
<asp:Label runat="server" ID="lblEmcnct" Text="Emergency Contact Number" AssociatedControlID="txtEmrCnct" CssClass="control-label" />
<asp:TextBox runat="server" ID="txtEmrCnct" CssClass="form-control" />
Button code saving the data in database
<button type="button" class="btn btn-primary" aria-label="Left Align" runat="server" onserverclick="btnContactInfoSave_click">
code for aspx.cs page
btnContactInfoSave_click code for saving the data in database.
protected void btnContactInfoSave_click(object sender, EventArgs e)
{
string[] ContactInfoData = new string[4];
ContactInfoData[0] = GlobalVars.UserEmail;
ContactInfoData[1] = txtCnct.Text;
ContactInfoData[2] = txtAltCnct.Text;
ContactInfoData[3] = txtEmrCnct.Text;
Utilities.sqlUploadContactInfoData(ContactInfoData);
}
}
public static void sqlUploadContactInfoData(string[] Userdata)
{
using (SqlConnection sqlConn = jPortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "spUploadContactInfoData";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#txtCnct", Userdata[0].ToString());
cmd.Parameters.AddWithValue("#txtAltCnct", Userdata[1].ToString());
cmd.Parameters.AddWithValue("#txtEmrCnct", Userdata[2].ToString());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}
After entering the data when I am trying to save the data it is not saving the data. button is not triggering. Any wrong in this code..???
Try with This. This is the way to Insert data into DB
SQL connection code for connecting database...
public static void sqlUploadContactInfoData(string[] Userdata)
{
using (SqlConnection sqlConn = jPortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "spUploadContactInfoData";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#txtCnct", txtCnct.Text);
cmd.Parameters.AddWithValue("#txtAltCnct", txtAltCnct.Text);
cmd.Parameters.AddWithValue("#txtEmrCnct", txtEmrCnct.Text);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}
From your web from designer double click on the button check weather it pointing to the Button event you expected to be invoked.else this will create a event handler for you.
If you are assigning the click handler in code behind, make sure that it is not inside an IsPostBack == false check :
make sure CausesValidation = "false" attribute of button like:
runat="server" and OnClick="btnContactInfoSave_click" check these attribute exist in your asp button
Try button in this way:
<asp:Button ID="AddMore_Button" class="btn btn-primary" runat="server" Text="" OnClick="btnContactInfoSave_click" />

.Net - I want to compare a value from a TextBox with Database values

I have this InsertItemTemplate to insert, in my case, diagnoses ("diagnósticos" in portuguese as you can see).
<InsertItemTemplate>
<asp:HiddenField ID="DiagnosticoID" Value='<%# Eval("Diagnostico_ID") %>' runat="server" />
<asp:TextBox ID="DiagnosticoNome" MaxLength="20" Text='<%# Bind("Diagnostico_Nome") %>' runat="server" />
<!--OTHER VALIDATORS HERE-->
<asp:CustomValidator
ErrorMessage="Esse Diagnóstico já existe!!!"
ControlToValidate="DiagnosticoNome"
OnServerValidate="MesmoDiagnostico_ServerValidate"
Display="Dynamic"
ForeColor="#FF000" runat="server" />
<asp:Button ID="Adicionar" runat="server" Text="Adicionar" CommandName="Insert" />
<asp:Button ID="Cancelar" runat="server" Text="Cancelar" CommandName="Cancel" />
</InsertItemTemplate>
So, I created a CustomValidator, because I want to check if the name of the diagnosis already exists on the database. I made a search about how I can work with the SqlConnection on C# but still can't do it. What I'm planning to do is to Select all the name of the diagnoses I have and compare with the diagnosis I want to Insert. If it already exists, then there's an error, else, everything is ok!
For now, I have this:
protected void MesmoDiagnostico_ServerValidate(object source, ServerValidateEventArgs args)
{
SqlConnection db = new SqlConnection("Data Source=localhost;");
db.Open();
SqlCommand cmd = new SqlCommand("Select Diagnostico_Nome from Diagnosticos", db);
}
Thanks for the help! :P
Use a COUNT(*) and a Where clause in your Sql Statement.
Something like (assuming source is the text you want to compare?),
SqlCommand cmd = new SqlCommand("Select COUNT(*) from Diagnosticos Where Diagnostico_Nome=#Diagnostico_Nome", db);
cmd.Parameters.AddWithValue("#Diagnostico_Nome", (string)source);
var count = (int)cmd.ExecuteScalar();
if (count > 0)
// This exists in the DB
I would also recommend wrapping your SqlConnection and SqlCommand in using blocks.

Categories