Checking Username Available Doesn't Work - c#

I have an asp.net web forms application which when a user tabs out of the username field it checks my database to see if its available or not but the issue I am having is that it always seems to fall into the exists even if it doesn't.
I have watched many videos on it and also read many articles but I can't get it to work at all.
I have provided all my code below.
Config
<add name="PaydayLunchConnectionString1" connectionString="Data Source=********\*******;Initial Catalog=************;Integrated Security=True"
providerName="System.Data.SqlClient" />
HTML
<asp:GridView ID="tblUsers" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlUsers" GridLines="None" Width="15%">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
</asp:GridView>
<asp:SqlDataSource ID="SqlUsers" runat="server" ConnectionString="<%$ ConnectionStrings:PaydayLunchConnectionString1 %>" SelectCommand="SELECT [Name] FROM [Users] WHERE [name] != 'Admin'"></asp:SqlDataSource>
<asp:Label ID="removeUserNotExist" runat="server" Text="The user entered does not exist. Please try again." Visible="false" style="color: red"></asp:Label>
<asp:Label ID="removeUserExists" runat="server" Text="The user entered exists." Visible="false" style="color: green"></asp:Label>
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="txtRemoveUser" CssClass="col-sm-offset-2 col-sm-3 control-label">Enter Name To Be Removed</asp:Label>
<div class="col-sm-3">
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" AutoPostBack="true" OnTextChanged="txtRemoveUser_TextChanged" />
</div>
</div>
Code Behind
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
protected void txtRemoveUser_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtRemoveUser.Text))
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Name != #Name", conn);
cmd.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
removeUserNotExist.Visible = true;
removeUserExists.Visible = false;
}
else
{
removeUserNotExist.Visible = false;
removeUserExists.Visible = true;
}
}
}
DB Details
Table Name = Users
Columns = ID, Name, Password
Users = Test, Test2
If I enter 'Test' in the field and tab out, I get the correct message (Exists) but if i then enter 'ABC' I still get the 'Exists' message.

If there is more than 1 user in your database, this query will always produce rows. Hence, your if statement always produces the same result:
SELECT * FROM Users WHERE Name != #Name
If you want to check if a user name exists, simply check for equality.
SELECT * FROM Users WHERE Name = #Name
If that one returns a row, the user name exists. Otherwise it doesn't.
A better solution would be to use 1 in the select, since that prevents the database to return all row data, a small performance improvement:
SELECT 1 dummy FROM Users WHERE Name = #Name

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.

Add new data to gridview without refreshing entire gridview

I know the title might make my question look like a duplicate so please read the complete question first.
I have 3 dropdowns in my webform and based on those parameters the data is retrieved from the database and my gridview is populated. What I need is that once a result is displayed, if the user changes the parameters, the new retrieved data should be displayed below the old data. But currently my gridview is refreshing entirely and only the data based on new parameters is displayed.
I have read that one way is to use viewstate but I dont understand what it is. Can someone please help? Thank you.
Ok, so this is a difficult question. It is rather easy to filter, and have a cumulative filter.
So, say we have this screen:
And lots more rows.
So, I can say lets filter by a city.
So this:
Note how we do allow multiple city in the multi-select drop down.
So, I now have this:
Now, lets select those ONLY with a description.
So this:
And then say only active ones. So, this:
So, above is quite easy to setup. Note how any option NOT selected is left out of the critera.
but, a BIG problem exists in the above.
What happens if I want Active from say B.C. but NOT active from Alberta???
I can't do that, and hence your problem.
What we could do however is add a button to above to SAVE the resulting filter, and put the "list" of filters say into a list box or collection.
we then have a search button to search on our collection of filters.
Let me see if this can work - I'll add to above a "box" or collection of each filter.
I would think a union query with distinct row for each filter would do the trick.
So, above example is not too hard - a "cumulative" filter. In fact, the code patter for 2 or 15 filters is quite easy to do here.
However, adding up separate filter requests and combine them? That is somewhat difficult to do.
Edit: Multiple filters
so, while in above, I could say filter by city and get all active, but THEN I want to filter by another city, and get all NON active!!!
That's the problem here.
So, we would have to add code to SAVE the filter. And the HUGE problem with that is how then do we save each filter to "add up" each filter set we want?
We could try and save the raw SQL, but such SQL would be subject to sql injection, and we want to always use parameters.
So, we can and could adopt a design in which we SAVE the resulting SqlCommand object. And then merge the results.
So, now our UI becomes like this:
Lets grab and filter all those from city Edmonton, but Active,
so, this:
We now hit save filter and this:
And now we filter by say City = Banff, but don't care about active or not.
So we have this:
We then save that filter - and now we have this:
I now hit the filter button below the list of filters, and we get this:
So, how does this code work?
Well, I simple saved the Sqlcommand object to a collection (list), and thus combine the results.
So, first our markup at the top for the filter stuff.
<h4>Filters</h4>
<div style="float:left">
<asp:Label ID="Label1" runat="server" Text="Search Hotel"></asp:Label>
<br />
<asp:TextBox ID="txtHotel" runat="server"></asp:TextBox>
</div>
<div style="float:left;margin-left:20px">
<asp:Label ID="Label2" runat="server" Text="Search City"></asp:Label>
<br />
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
</div>
<div style="float:left;margin-left:20px">
<asp:Label ID="Label3" runat="server" Text="Must Have Description"></asp:Label>
<br />
<asp:CheckBox ID="chkDescripiton" runat="server" />
</div>
<div style="float:left;margin-left:20px">
<asp:Label ID="Label4" runat="server" Text="Show only Active Hotels"></asp:Label>
<br />
<asp:CheckBox ID="chkActiveOnly" runat="server" />
</div>
<div style="float:left;margin-left:20px">
<asp:Button ID="cmdSearch" runat="server" Text="Search" CssClass="btn" OnClick="cmdSearch_Click"/>
</div>
<div style="float:left;margin-left:20px">
<asp:Button ID="cmdClear" runat="server" Text="Clear Fitler" CssClass="btn" OnClick="cmdClear_Click"/>
</div>
<div style="float:left;margin-left:20px">
<asp:Button ID="cmdTest" runat="server" Text="Save Filter"
CssClass="btn" OnClick="cmdTest_Click"
OnClientClick="return myfilterprompt()"
/>
<asp:HiddenField ID="HFilterName" runat="server" ClientIDMode="Static"/>
<script>
function myfilterprompt() {
sFilter = ""
sFilter = prompt('Enter name for filter ')
if ( (sFilter === null) || (sFilter === "") ){
return false
}
$('#HFilterName').val(sFilter)
return true
}
</script>
</div>
<div style="float:left;margin-left:30px;width:190px">
<asp:ListBox ID="lstFilters" runat="server" Width="100%" Height="100px"
DataTextField="sFilterName" >
</asp:ListBox>
<asp:Button ID="cmdMultiFilter" runat="server" Text="Filter"
CssClass="btn" OnClick="cmdMultiFilter_Click" style="float:left" />
<asp:Button ID="cmdMultiClear" runat="server" Text="Clear"
CssClass="btn" OnClick="cmdMultiClear_Click" style="float:right"/>
</div>
then below above is our grid:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID"
CssClass="table" Width="60%" ShowHeaderWhenEmpty="true">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Province" HeaderText="Province" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Active" HeaderText="Active" />
</Columns>
</asp:GridView>
So, code to load:
List<MyFilter> MyFilters = new List<MyFilter>();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
SqlCommand cmdSQL = new
SqlCommand("SELECT * FROM tblHotels WHERE ID = 0");
LoadGrid(cmdSQL);
Session["MyFilters"] = MyFilters;
}
else
MyFilters = (List<MyFilter>)Session["MyFilters"];
}
public void LoadGrid(SqlCommand cmdSQL)
{
DataTable rstData = MyRstP(cmdSQL);
GridView1.DataSource = rstData;
GridView1.DataBind();
}
And now our search button:
protected void cmdSearch_Click(object sender, EventArgs e)
{
SqlCommand cmdSQL = GetMyCommand();
LoadGrid(cmdSQL);
}
SqlCommand GetMyCommand()
{
string strSQL = "SELECT * FROM tblHotels ";
string strORDER = " ORDER BY HotelName";
string strFilter = "";
SqlCommand cmdSQL = new SqlCommand();
if (txtHotel.Text != "")
{
strFilter = "(HotelName like #HotelName + '%')";
cmdSQL.Parameters.Add("#HotelName", SqlDbType.NVarChar).Value = txtHotel.Text;
}
if (txtCity.Text != "")
{
if (strFilter != "") strFilter += " AND ";
strFilter += "(City Like #City + '%') ";
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtCity.Text;
}
if (chkActiveOnly.Checked)
{
if (strFilter != "") strFilter += " AND ";
strFilter += "(Active = 1)";
}
if (chkDescripiton.Checked)
{
if (strFilter != "") strFilter += " AND ";
strFilter += "(Description is not null)";
}
if (strFilter != "") strSQL += " WHERE " + strFilter;
strSQL += strORDER;
cmdSQL.CommandText = strSQL;
return cmdSQL;
}
And now our save the filter button code:
protected void cmdTest_Click(object sender, EventArgs e)
{
MyFilter OneFilter = new MyFilter();
OneFilter.sFilterName = HFilterName.Value;
OneFilter.cmdSQL = GetMyCommand();
MyFilters.Add(OneFilter);
lstFilters.DataSource = MyFilters;
lstFilters.DataBind();
}
public class MyFilter
{
public string sFilterName { get; set; }
public SqlCommand cmdSQL = new SqlCommand();
}
And our multi-filter code button.
Now, for large data sets - not a great idea, but a start:
protected void cmdMultiFilter_Click(object sender, EventArgs e)
{
List<DataTable> MyTables = new List<DataTable>();
foreach (MyFilter OneFilter in MyFilters)
{
DataTable rstDT = MyRstP(OneFilter.cmdSQL);
MyTables.Add(rstDT);
}
DataTable rstData = MyTables[0];
for (int i = 1;i < MyTables.Count;i++)
{
rstData.Merge(MyTables[i]);
}
GridView1.DataSource = rstData;
GridView1.DataBind();
}
so, you can build list up of "filters" and display them in a listbox and then have a filter button that merges all of the filtering.
And one more helper routine I used:
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
These systems can be really nice. Often a group of managers will say, lets grab all customers from west coast. Yuk - too many. Ok, only those with purchases in last 2 months - ah, that's nice.
then they say, lets get all customers who never purchased anything, but from the south - and add those to the list - but only active on our mailing list.
So, this type of slice and dice - get some of those, and then get some of these, and then combine them?
This type of business query system and being able to combine these, and those, and them, and then toss in a few more? Often they will keep going say until such time they get say 10,000 results (which happens to be how many catalogs they have left they would like to send out).
So, I solved my problem by using a little outside the box thinking. I am posting it here for anyone visiting this question or having a same problem in the future could see this:
So what I did is that I extracted the data from the database based on the parameters selected by the user from the dropdowns. In the database, I had created a temp table to store the extracted temporarily. So I inserted the data into that temporary table and used that table to populate the gridview. I had to add a reset button, when the user clicked it the all the data is deleted from the temp table and also the page reset to its default with gridview not visible and dropdowns having no selection.

GridView Update button execute update SQL Server stored procedure

SQL Server stored procedure accepts the parameters, current company name, new company name and whether it already exists which has a default value. When the edit button is clicked on the front end UI, the grid view allows me to edit the company name. This shows an 'Update' button - when this is clicked - the code parses however nothing updates and company name does not update either.
Breakpoint is set and stepped through and #CurrentCompanyName is returned as null. Not sure how to fix this.
Aspx:
<asp:GridView ID="CompanyTable" runat="server"
OnRowEditing="CompanyTable_RowEditing"
OnRowCancelingEdit="CompanyTable_RowCancelingEdit"
OnRowUpdating="CompanyTable_RowUpdating"
OnPageIndexChanging="CompanyTable_PageIndexChanging"
PageSize="20" Font-Underline="False" AllowPaging="True">
<HeaderStyle Width="150px" />
<Columns>
<asp:TemplateField>
<HeaderStyle Width="200px" />
<ControlStyle CssClass="ButtonDesigntwo" />
<ItemTemplate>
<asp:LinkButton ID="Edit" ButtonType="Button" runat="server" CommandName="Edit" Text="Edit" />
<asp:LinkButton ID="Delete" ButtonType="Button" runat="server" CommandName="Delete" Text="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="Update" ButtonType="Button" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="Cancel" ButtonType="Button" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="tableHeaderStyle" />
<PagerSettings Mode="NumericFirstLast" />
<PagerStyle CssClass="pager" BorderColor="Black" ForeColor="White" Font-Underline="False" />
<RowStyle CssClass="tableRowStyle" />
</asp:GridView>
Method code:
protected void CompanyTable_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand("[updateCompanyName]", cn))
{
TextBox name = CompanyTable.Rows[e.RowIndex].FindControl("CompanyTable") as TextBox;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CurrentCompanyName", name);
cmd.Parameters.AddWithValue("#NewCompanyName", CompanyInputTextBox.Text).Direction = ParameterDirection.Input;
SqlParameter objisExists = new SqlParameter("#isExists", SqlDbType.Int);
objisExists.Direction = ParameterDirection.Output;
cmd.Parameters.Add(objisExists);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
int isExists = Convert.ToInt32(cmd.Parameters["#isExists"].Value.ToString());
if (isExists == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "111", "AddCompanyUpdating();", true);
}
else if (isExists == 1)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "111", "CompanyNotUpdatedValidation();", true);
}
}
// Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
CompanyTable.EditIndex = -1;
// Call ShowData method for displaying updated data
BindData();
}
Stored procedure:
ALTER PROCEDURE [dbo].[updateCompanyName]
#CurrentCompanyName VARCHAR(50),
#NewCompanyName VARCHAR(50),
#IsExists INT = 0 OUT
AS
BEGIN
DECLARE #CompanyID INT
SELECT #CompanyID = CompanyID
FROM company
WHERE companyname = #CurrentCompanyName
BEGIN
IF EXISTS (SELECT CompanyName
FROM company
WHERE companyname = #NewCompanyName )
BEGIN
SET #IsExists = 1
END
ELSE
BEGIN
UPDATE COMPANY
SET CompanyName = #NewCompanyName
WHERE companyid = #CompanyID
SET #IsExists = 0
END
END
PRINT #isexists
END
You are defining name as a textbox in this line:
TextBox name = CompanyTable.Rows[e.RowIndex].FindControl("CompanyTable") as TextBox;
Then you try to set the value of your parameter to the textbox in this line:
cmd.Parameters.AddWithValue("#CurrentCompanyName", name);
When what you SHOULD be doing, is setting the parameter value to the TEXT that is IN the textbox:
cmd.Parameters.AddWithValue("#CurrentCompanyName", name.Text);
EDIT:
Since name itself is NULL when you are hovering over it, that means that you have not correctly defined it in this line:
TextBox name = CompanyTable.Rows[e.RowIndex].FindControl("CompanyTable") as TextBox;
Stop the code in the debugger and open a quick view into CompanyTable, and see if you can figure out the correct way to define the textbox you are looking for.
EDIT 2: In defining your TextBox, you are doing FindControl("CompanyTable"), but according to your markup, "CompanyTable" is the ID of your GridView, not a textbox. In fact, I don't see any markup anywhere for a textbox in the first code sample you posted.

How to show fixed amount of rows in asp.net gridview

So here I have few gridviews in a row in asp.net. The problem now is it is inconsistent where some gridview would have 5 data and some would have 10. It looks ugly and since I needed to print. It's crucial.
I wanted to show max 15 rows. It is databound from the database which the user would fill up the subjects taken form(up to 15 rows). And if any of the rows doesn't have any of the data. It would leave it blank instead(note that the database didn't fills up to 15 rows.. only what is entered by the user). I've done some research but only found a few that might be related but using javascipt/changing current SQL given. I'm not allowed to use any javascript in the site (supports later would be a problem). And since I'm an intern. The sql code is given to me. I just need to implement it. What can I do to show fixed amount of rows in gridview? Is there any attribute that I can use in gridview to fill up the empty space to 15 rows?
aspx file
<asp:GridView ID="GridViewResult" runat="server" AutoGenerateColumns="False" EmptyDataText="NO RECORD" Font-Size="Small"
GridLines="Both" CellPadding="1" Height="101px" Width="100%" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="Subjects">
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("Subjects") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="25px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Grade">
<ItemTemplate>
<asp:Label ID="lbl1" runat="server" Text='<%# Eval("Grade") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="25px" />
</asp:TemplateField>
</Columns>
<HeaderStyle Font-Bold="True" HorizontalAlign="Center" Height="40px"/>
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<FooterStyle HorizontalAlign="Center" />
</asp:GridView>
And the back code
Protected void LoadgvResult1()
{
SqlCommand cmdgvKep1 = new SqlCommand();
cmdgvKep1.Connection = conn;
cmdgvKep1.CommandType = CommandType.Text;
cmdgvKep1.CommandText = " SELECT ROW_NUMBER() OVER(ORDER BY Grade ASC) AS Numb, Subjects, Grade ";
cmdgvKep1.CommandText += " FROM Result_SMU ";
cmdgvKep1.CommandText += " WHERE siri = '" + siri + "' ";
conn.Open();
SqlDataAdapter adaptergvKep1 = new SqlDataAdapter(cmdgvKep1);
DataSet dsgvKep1 = new DataSet();
adaptergvKep1.Fill(dsgvKep1, "Result_SMU");
GridViewResult1.DataSource = dsgvKep1;
GridViewResult1.DataBind();
conn.Close();
}
There was a lot of problems with your code.
1)Your data access layer should not be on the same place when you are
DataBind the Grid
2)You should not use global SqlConnection. Connection pool is your
friend. Also if exception occurs your connection will never be closed.
3)Your query should use sql parameters to prevent from Sql Injection.
4) You should wrap SqlDataAdapter in using statement, so it will be disposed
after Fill.
If I understood you correctly you want to fill the grid with dummy records for some reason in the C# when the number of the records are under 15, you can add dummy rows to the fetch dataset like this.
int countRows = dsgvKep1 .Tables[0].Rows.Count;
int dummyRecords = 0;
if(countRows < 15)
{
dummyRecords = 15 - countRows;
}
for (int i = 0; i < dummyRecords; i++)
{
DataTable tbl = dsgvKep1.Tables[0];
DataRow row = tbl.NewRow();
//add dummy values if you want
//row["ColumnName"] = value;
tbl.Rows.Add(row);
}
I advise you to fix the 4 pointers which I gave you. From what I see you are intern and this will be good for you in long term.
I wrote how to create a simple data access layer in this question: checking user name or user email already exists , here you can see data layer, disposing sqlDataAdapter, preventing of not close sql connection when exception occur and also preventing sql injection using SqlComand.Parameters.

.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