Print Data of only first row of database instead of whole table - c#

I need to output the data that's only on the first row, but it is printing all the data added to the database table. Here is the data:
For example, It should print only "Not Very Nice" and the message of ID 27, but not the second row that has ID 28.
Here is the code:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class feedback1 : System.Web.UI.Page
{
SqlConnection con;
string cons = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(cons);
con.Open();
cmd = new SqlCommand("insert into feedback(username,message) values('" + TextBox1.Text + "','" + TextBox2.Text +"')", con);
cmd.ExecuteNonQuery();
}
}
Here is the output..
This is the output page code..
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1" EnableModelValidation="True" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" GridLines="None">
<Columns>
<asp:BoundField DataField="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="username" HeaderText="username" SortExpression="username" />
<asp:BoundField DataField="message" HeaderText="message" SortExpression="message" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" OnSelecting="SqlDataSource1_Selecting" SelectCommand="SELECT * FROM [feedback]"></asp:SqlDataSource>
<div>
</div>
</form>

This is just a case of modifying your SQL-query:
Selecting the 1st row:
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
OnSelecting="SqlDataSource1_Selecting"
SelectCommand="SELECT * FROM [feedback] LIMIT 1">
</asp:SqlDataSource>
Selecting specific ID:
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
OnSelecting="SqlDataSource1_Selecting"
SelectCommand="SELECT * FROM [feedback] WHERE [id] = REPLACE_WITH_YOUR_NUMBER">
</asp:SqlDataSource>
"Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a limited number of records."
Please see: https://www.w3schools.com/sql/sql_top.asp
NOTE
Your program is vulnerable to SQL-injections.
Please modify your input to sanitize your query before its executed.
protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(cons);
con.Open();
string txtb1= TextBox1.Text,
txtb2= TextBox2.Text;
sqlCommand.CommandText = "select * from product where name = #name";
cmd = new SqlCommand("insert into feedback(username,message) values('" + #txtb1 + "','" + #txtb2 +"')", con);
cmd.Parameters.AddWithValue("txtb1", txtb1);
cmd.Parameters.AddWithValue("txtb2", txtb2);
cmd.ExecuteNonQuery();
}
๐Ÿ˜ Stop right there! ๐Ÿšจโœ‹! This is the police ๐Ÿ‘ฎ I hope you've read up on the laws around this block. You're in violation of penal code 404 - Database Not Found!
If you post another ๐Ÿ“– sql-vulnerable ๐Ÿ“  post again in this neighborhood ๐Ÿ ๐Ÿ 
I'm gonna have to ๐Ÿ”’ arrest you ๐Ÿ”’
No ticket today ๐Ÿ‘ฆ
๐Ÿ“ŸThis is just a warning โš ๏ธ be careful next time ๐Ÿšง

Depending on whether you always want that specific row with ID 27, or whether you just want the "first" row, whatever that happens be, you can write either
SELECT * FROM feedback WHERE id = 27
or
SELECT * FROM feedback LIMIT 1
respectively.
P.S. This is given using MySQL syntax, since that's what you tagged the question with. However, from your code I can see that you use a SqlConnection object to connect, which is only compatible with Microsoft SQL Server. If you're using SQL Server and not MySQL, then please change your question tags to mention the correct product. You would also need to alter the second query in my example above to SELECT TOP 1 FROM feedback, as TOP is used in SQL Server, whereas LIMIT achieves the same effect in MySQL.

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.

delete row from gridview sql

I want to be able to delete a row when I click on the delete button on that gridview. I have the aspx page and the code behind as well as the app code. The DeletePaymentCondition runs the store procedure to delete the row. But somehow the overall code doesnt work
aspx
<asp:GridView ID="gridview1" runat="server" HorizontalAlign="left" AutoGenerateColumns="false" CssClass="table table-bordered " GridLines="None"
AllowSorting="True" OnRowDeleting="OnRowDeleting">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="left" HeaderText="Payment Condition" HeaderStyle-CssClass="OGColor" HeaderStyle-ForeColor="white" SortExpression="monthToQuarters">
<ItemTemplate>
<span style="font-size:12px; color: #2980b9; text-align:left">
<asp:Label ID="lblUserId" runat="server" Visible="true" Text="<%# bind('payConditionId')%>"/>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/>
</Columns>
</asp:GridView>
cs
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblEmpID = (Label)gridPayment.Rows[e.RowIndex].FindControl("lblUserId"); //This is Table Id load on Label1
int id = Convert.ToInt32(lblEmpID.Text.ToString());
dsPayment = objcommission.Delete(id);
gridPayment.DataSource = dsPayment.Tables[0];
gridPayment.DataBind();
}
app code
public DataSet DeletePayment(int id)
{
DataSet dsGetAllPayment;
dsGetAllPaymentCondition = SqlHelper.ExecuteDataset(OGconnection, CommandType.Text, "Delete FROM tblPay where pay ='" + id + "'");
return dsGetAllPayment;
}
You shoul execute two different SQL, one for the delete and a new select one to retreive the new data.
The DELETE should be executed using in a NonQuery because it does not return rows (only the number of rows affected).
public DataSet DeletePaymentCondition(int ids)
{
int rowsAffected = SqlHelper.ExecuteNonQuery(OGconnection, CommandType.Text, "Delete FROM [Accounting].[dbo].[tblPayConditions] where payConditionId ='" + ids + "'");
DataSet dsGetAllPaymentCondition = SqlHelper.ExecuteDataSet(OGconnection, CommandType.Text, "Select * FROM [Accounting].[dbo].[tblPayConditions]");
return dsGetAllPaymentCondition;
}
As a good praxys, you should consider changing it into parametrized queries. In this case it is safe because of the integer conversion, but in similar code with string parameters you would be prone to SQL Injection attacks
I got the solution. I've made changes to the cs file and as well as the code provided by bradbury9.
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(gridPaymentCondition.DataKeys[e.RowIndex].Value.ToString());
dsPaymentCondition = objcommission.DeletePaymentCondition(index);
gridPaymentCondition.DataSource = dsPaymentCondition.Tables[0];
updatePaymentConditionsWithoutRefresh();
}

Custom SQL Select statement not displaying data in GridView

SELECT
LeagueTable.P,
LeagueTable.W,
LeagueTable.D,
LeagueTable.L,
LeagueTable.GF,
LeagueTable.GA,
LeagueTable.GD,
LeagueTable.Pts,
Team.Team_name,
LeagueTable.Team_ID
FROM LeagueTable
INNER JOIN Team
ON LeagueTable.Team_ID = Team.Team_ID
I've got the user to enter a team name on start up that is entered into the Team table, which redirects to a webpage with a league table. The league table initially contains no data but it should be displaying a row with the users input once the user has gotten to this page.
However this query shows the GridView as blank. What's wrong with it?
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" EmptyDataText="No teams entered into the table.">
<Columns>
<asp:BoundField DataField="P" HeaderText="P" SortExpression="P" />
<asp:BoundField DataField="W" HeaderText="W" SortExpression="W" />
<asp:BoundField DataField="D" HeaderText="D" SortExpression="D" />
<asp:BoundField DataField="L" HeaderText="L" SortExpression="L" />
<asp:BoundField DataField="GF" HeaderText="GF" SortExpression="GF" />
<asp:BoundField DataField="GA" HeaderText="GA" SortExpression="GA" />
<asp:BoundField DataField="GD" HeaderText="GD" SortExpression="GD" />
<asp:BoundField DataField="Pts" HeaderText="Pts" SortExpression="Pts" />
<asp:BoundField DataField="Team_name" HeaderText="Team_name" SortExpression="Team_name" />
<asp:BoundField DataField="Team_ID" HeaderText="Team_ID" SortExpression="Team_ID" />
</Columns>
</asp:GridView>
protected void NewTeamBtn_Click(object sender, EventArgs e)
{
string qry1 = "INSERT into Team (Team_name) VALUES (#Team_name)";
using (SqlCommand cmd = new SqlCommand(qry1, con))
{
cmd.Parameters.Add(("#Team_name"), SqlDbType.VarChar).Value = NewTeamTxtBox.Text;
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Redirect("EnterData.aspx");
}
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SportsData2ConnectionString %>" SelectCommand="SELECT LeagueTable.League_ID, LeagueTable.Team_ID, LeagueTable.P, LeagueTable.W, LeagueTable.D, LeagueTable.L, LeagueTable.GF, LeagueTable.GA, LeagueTable.GD, LeagueTable.Pts, Team.Team_name FROM LeagueTable INNER JOIN Team ON LeagueTable.Team_ID = Team.Team_ID"></asp:SqlDataSource>
Based on your comments it appears you may be inserting data into your Team table, but when you run the select statement you have in your SQL Data Source you will notice you have an Inner Join. That Inner Join means that if the team Id is not in either one of the 2 tables you are joining then no results will be returned.
I don't see your sql data source code, but another possible point of failure is the TeamID you pass into that control. There are 3 questions that come to my mind for making sure you get valid data.
1) Where are you getting it from?
2) Is it valid and in both tables?
3) Are you rebinding the gridview after setting that value?
Edit
What you want to do does not at all match your question at this point. You should edit your title and question.
I would use something like this for your insert.
DECLARE #TeamID as INT
INSERT into Team (Team_name) VALUES (#Team_name)
SELECT #TeamID = SCOPE_IDENTITY();
INSERT into LeagueTable Team_ID VALUES #TeamID
this post will help Scope_Identity vs ##Identity
this stack question will help too.

Checking Username Available Doesn't Work

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

ASP.NET Page does not refresh after running a DELETE SQL Query

I am using VS2005. Currently I have a delete linkButton in my gridview, and if I presses on it to delete a row, the GridView goes empty, and I will have to click on the link again to access the page.
Below is my codefor .aspx:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" ondatabound="gv_DataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="UserSelection" OnCheckedChanged="UserSelector_CheckedChanged" runat="server" />
<asp:LinkButton ID="lnkDelete" runat="server" onclick="lnkDelete_Click" Text="Delete" CommandArgument='<%# Eval("Employee") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below is my code for .cs
protected void lnkDelete_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlDataSource1.SelectCommand = "DELETE FROM [UserDB]where Employee like '%"+stid+"%'";
SqlDataSource1.DataBind();
}
I have tried assigning my delete query to SqlDataSource1 and select query to source2, but if that's the case, my delete query would not work.
I have also tried using IsPostBack on my PageLoad method, but the GridView goes empty as well after clicking on the delete button.
Currently both of my queries are assigned to SqlDataSource1, and once the query is deleted, the page just go blank, although the query is deleted.
May I know how can I refresh the page or reload the GridView table after the delete query is ran?
Thank you.
Thanks to the help from you guys, the problem is solved. Currently my working code is as follows:
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlConnection conn = new SqlConnection("DATA-SOURCE");
string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",stid);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
SqlDataSource1.SelectCommand = "SELECT * FROM [UserDB]";
SqlDataSource1.DataBind();
Response.Redirect("/Project/UserList.aspx");
I used a sql connection string for the delete query, and sqldatasource for the select query afterwards, finally refreshed the page by using response.redirect. Hope it helped newbies like me who met this error too.
Great thanks to all who provided help
Why are you assigning a DELETE command to the SelectCommand property ?
Just run the DELETE on a separate SqlCommand instance with ExecuteNonQuery and commit. Another option is to use DeleteCommand of the existing SqlDataSource.
Another point:
The way you build the DELETE SQL is vulnerable to a serious security problem called SQL injection - easiest and best way to avoid that is to use bind parameters!
First you should read up on what databinding in ASP.NET can do for you. (Then you won't have to write any codebehind for this scenario.)
Example: (Not tested in VS)
You should use the SqlDataSource's DeleteCommand to set the delete command and its parameters like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="..."
SelectCommand="..."
DeleteCommand="DELETE FROM [UserDB] WHERE Employee=#Employee">
<DeleteParameters>
<asp:Parameter Name="Employee" />
</DeleteParameters>
</asp:SqlDataSource>
And the on the GridView, you should set the DataKeyNames property, and inside the ItemTemplate's Linkbutton you should set the CommandName property to "Delete" as shown below:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
ondatabound="gv_DataBound" DataKeyNames="Employee"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="UserSelection" runat="server"
OnCheckedChanged="UserSelector_CheckedChanged" />
<asp:LinkButton ID="lnkDelete" runat="server"
onclick="lnkDelete_Click" Text="Delete"
CommandArgument='<%# Eval("Employee") %>'
CommandName="Delete" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Try like this
protected void lnkDelete_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlConnection conn = new SqlConnection(<put your connectionstring here>);
string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",stid);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
BindTheGridView();
//or you can use SelectCommand of your SqlDataSource1 and can bind again simply.
}
EDIT:
public void BindTheGridView()
{
SqlConnection conn = new SqlConnection(Connstring);
string sql = "Select * from [UserDB]";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtb = new DataTable();
da.Fill(dtb);
conn.Close();
SqlDataSource1.DataSource = dtb;
SqlDataSource1.DataBind();
}
And you can call this for any time to bind the values.
It's wrong to run change operation (DELETE in your example) as a SelectCommand. SelectCommand must be used as it called - only to SELECTs.
Run the DELETE query separately, then run a SELECT command to show the relevant records for the grid.
SqlDataSource1.SelectCommand = "DELETE FROM [UserDB]where Employee like '%"+stid+"%'";
SqlDataSource1.DataBind();
Why are you using Delete query in SelectCommand. The query is open to SqlInjection attack. I would have used a stored procedure and verify the parameter before passing it to the procedure.
Moreover the Grid won't show/bind any data as your code is not return any data back. It is just deleting the data.
I guess you can do a gridview.DataBind() instead of sqlDatasource.databind. The gridviews databind internally performs the sqldatasource databind and also refreshes the gridview.

Categories