I have an Asp.net application and I am trying to delete a row from my 'Users' db if the user submits the requests via the web but I can't seem to get it to work.
HTML
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Remove User</h3>
</div>
<div class="panel-body">
<asp:Label ID="lbRemoveUser" runat="server" Text="Remove User">
<b>Enter Full Name</b>
</asp:Label>
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" AutoPostBack="true" OnTextChanged="txtRemoveUser_TextChanged" />
<asp:Label ID="removeUserNotExist" runat="server" Text="The user entered does not exist." Visible="false" style="color: red"></asp:Label>
</div>
<div class="panel-footer">
<div class="text-center">
<asp:Button CssClass="btn btn-danger" ID="btnSubmitRemoveUser" runat="server" Text="Remove User" ToolTip="Click to remove the user from the list." OnClick="removeUserSubmitButton_Click" />
</div>
</div>
</div>
<!-- Confirm Removal Modal-->
<div class="modal fade" id="confirmRemoveUserModal">
<div class="modal-dialog" style="margin-top: 55px">
<div class="modal-content">
<div class="modal-header ConfirmHeader">
<h4 class="modal-title" id="myModalLabel">Confirm Removal</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to remove <b><%=Session["txtRemoveUser"] %></b> from the payday lunch list?</p>
<p>If you don't, click 'No' and the user will not be removed.</p>
</div>
<div class="modal-footer ConfirmFooter">
<asp:Button id="btnRemoveConfirmYes" runat="server" CssClass="btn btn-success" Text="Yes" OnClick="btnRemoveConfirmYes_Click" ToolTip="Click to remove the user from the payday lunch list." />
<asp:Button id="btnRemoveConfirmNo" runat="server" CssClass="btn btn-warning" Text="No" OnClick="btnAllCloses_Click" ToolTip="Click to close this screen. The user will not be removed." />
</div>
</div>
</div>
</div>
Code I tried
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = " + txtRemoveUser.Text, conn);
conn.Close();
txtRemoveUser.Text = "";
Response.Redirect("/AdminSide/TaskList.aspx");
}
Like I said all I want is to delete the entry if it exists in my db. I already have a check to make sure that the entry exists in the 'Users' table
Do I need the SqlDataReader rd1 = cmd1.ExecuteReader(); as when I tried it, I got a server error "System.Data.SqlClient.SqlException: Invalid column name 'Test2'."
You are not using ExecuteNonQuery. You also have to wrap the user-name in apostrophes:
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = '" + txtRemoveUser.Text + "'", conn);
But you should always use sql parameters to prevent sql injection and other issues:
using(var cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = #Name", conn))
{
cmd1.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtRemoveUser.Text;
conn.Open();
cmd1.ExecuteNonQuery();
}
also use the using-statement on types that implement IDisposable like SqlCommand or -more important- SqlConnection to ensure that unmanaged resources are disposed.
Related
I have a dropdown value which selects customer name and also i have a
sales executive dropdown which selects executives name i want to
display Gridview table based on customer name selection but i am able
to display only its ID . i need to display their names instead of ID.
<div class="form-group">
<asp:Label class="control-label col-md-3 col-sm-3 col-xs-12" runat="server" Text="Customer Name"></asp:Label>
<div class="col-md-7 col-sm-6 col-xs-12">
<asp:DropDownList ID="customerDetails" runat="server" class="form-control col-md-7 col-xs-12" CssClass="mydropdownlist">
<asp:ListItem Enabled="true" Value="0">--Select Customer--</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<div class="form-group">
<asp:Label class="control-label col-md-3 col-sm-3 col-xs-12" runat="server" Text="Sales Executive"></asp:Label>
<div class="col-md-7 col-sm-6 col-xs-12">
<asp:DropDownList ID="salesExceutive" runat="server" class="form-control col-md-7 col-xs-12" CssClass="mydropdownlist">
<asp:ListItem Enabled="true" Value="0">--Select Sales Executive--</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<asp:Button ID="btnSearch" class="btn btn-primary"
runat="server" Text="Search" OnClick="btnSearch_Click" />
I have tried following.
protected void btnSearch_Click(object sender, EventArgs e)
{
if (customerText != "0" && salesExeText == "0")
{
string sqlQuery = #"SELECT * from app_order_master where
customer_id = " + customerText ;
using (DataTable dt = SMSDBHelperFE.ExecuteReaderDataTable(CommandType.Text, sqlQuery, null))
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
See the picture above instead of id i need to display name
Your Question is not fully understandable. But I think you are storing Customer Id in the table. And while retrieving data from app_order_master table and binding with gridview you are not Joining it with Customer table with the id. That's why you are not getting Customer name.As I don't know your table structure I couldn't help much.But you can self learn about joining from below link
https://www.w3schools.com/sql/sql_join.asp
http://www.sql-join.com/sql-join-types
https://www.tutorialspoint.com/sql/sql-using-joins
I wanted to display 10 recent news from database. I have used LIMIT 10 in sql query to display 10 recent news. I am using bootstrap.
I am getting only 1 news from the database. I know that here I have to use datalist or listview in design. But I don't know how to implement it using Bootstrap.
Default.aspx:
<div class="container">
<h1 class="main-module-title">Recent <span>News</span></h1>
<%-- <asp:datalist runat="server">
<ItemTemplate>--%>
<div class="row-fluid">
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3">
<a href="#">
<asp:Image runat="server" ID="ImgNews" class="img-responsive img-box img-thumbnail"/>
</a>
</div>
<div class="col-xs-12 col-sm-9 col-md-9">
<h4><asp:Label ID="newsheader" runat="server" Text=""></asp:Label></h4>
<p runat="server" style="text-align:justify" id="newscontent"> </p>
</div>
</div>
<hr/>
</div>
<%-- </ItemTemplate>
</asp:datalist>--%>
</div>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MySqlConnection conn = null;
string newsitem = null;
if (!(Request.QueryString["newstitle"] == null))
{
Page.Header.Title = Request.QueryString["newstitle"] + " - DubaiExporters ";
}
else
{
Page.Header.Title = "DubaiExporters - Dubai Business News - UAE Exports";
}
try
{
string connStr = ConfigurationManager.ConnectionStrings["mysqldbeConnectionString"].ToString();
string newssql = null;
newssql = "SELECT * FROM news WHERE status = b'1' AND linkstatus = b'1' ORDER BY datepublished DESC LIMIT 10";
conn = new MySqlConnection(connStr);
MySqlCommand cmd = new MySqlCommand(newssql, conn);
conn.Open();
MySqlDataReader r = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if(r.Read())//while(r.Read())
{
newsheader.Text = HttpUtility.HtmlDecode(r["newstitle"].ToString().Trim()).ToString();
newscontent.InnerHtml = HttpUtility.HtmlDecode(r["newsbrief"].ToString().Trim()).ToString();
ImgNews.ImageUrl = "~/images/newspictures/" + r["image"].ToString();
}
}
catch (MySqlException ex)
{
}
catch (Exception ex)
{
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
try the below template and bind the DataList to DataSource in the Page Load event inside !Page.IsPOstBack condition
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<div class="row-fluid">
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3">
<a href="#">
<asp:Image runat="server" ID="ImgNews" class="img-responsive img-box img-thumbnail" ImageUrl='<%# "~/images/newspictures/" + Eval("image")%>' />
</a>
</div>
<div class="col-xs-12 col-sm-9 col-md-9">
<h4><a href="#">
<asp:Label ID="newsheader" runat="server" Text='<%# Eval("newstitle") %>'></asp:Label></a></h4>
<p runat="server" style="text-align: justify" id="newscontent"><%# Eval("newsbrief") %></p>
</div>
</div>
<hr />
</div>
</ItemTemplate>
</asp:DataList>
In my website project, I made a register and login form, then I connected it to a database. The insertion was working. Now I added session to store the data of registration, but no data is getting inserted. In addition to this, I am not getting any change in codes too, where I made change if there is a session. Once it said that localhost refused to connect, but now the browser is not giving any error like that. Can anyone please help me figure out where the problem in my code is?
My C# code is:
protected void userRegister(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString;
string encoded_pass = encrypt_pass(Regi_Password.Text);
using(SqlConnection connection = new SqlConnection(constr))
{
string insertQuery = "insert into dbo.users(user_f_name,user_l_name,user_password,user_email,user_age, user_gender) values (#First_Name, #Last_Name, #Regi_Password, #Regi_Email, #Age, #Gender);";
SqlCommand com = new SqlCommand(insertQuery, connection);
connection.Open();
com.Parameters.AddWithValue("#First_Name", First_Name.Text);
com.Parameters.AddWithValue("#Last_Name", Last_Name.Text);
com.Parameters.AddWithValue("#Regi_Password", encoded_pass);
com.Parameters.AddWithValue("#Regi_Email", Regi_Email.Text);
com.Parameters.AddWithValue("#Age", Age.Text);
com.Parameters.AddWithValue("#Gender", Gender.SelectedValue);
try
{
com.ExecuteNonQuery();
com.CommandText = "Select * from dbo.users where email = " + Regi_Email.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
Session["User"]=dt.Rows[0]["user_f_name"];
Response.Redirect("default.aspx");
loginlabel.Text="Welcome, "+Session["User"];
connection.Close();
}
catch
{
Label1.Text = "Registration Error!";
}
}
The HTML is:
<form runat="server" method="post">
<div class="header">
<img id="icon" src="Images/logo.png">
<form>
<input type="text" id="search" placeholder="Search for people, place, locations">
<input type="submit" id="search_button" value="">
</form>
<span id= "login" runat="server" onclick="login();"><asp:Label ID="loginlabel" Text="" runat="server"></asp:Label></span>
</div>
<div>
<asp:ContentPlaceHolder id="Body" runat="server">
</asp:ContentPlaceHolder>
</div>
<div id="Sign_Up_Form" style="display: none">
<form class="modal-content animate">
<div class="input">
<div>
<div>Name</div>
<asp:TextBox CssClass="signUp_input" ID="First_Name" runat="server" placeholder="First Name" style="height: 20px; padding-left: 1px;"></asp:TextBox>
<asp:TextBox CssClass="signUp_input" ID="Last_Name" runat="server" placeholder="Last Name" style="height: 20px; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Email</div>
<asp:TextBox CssClass="signUp_input" ID="Regi_Email" runat="server" placeholder="Your email here" style="height: 20px; width:90%; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Password</div>
<asp:TextBox CssClass="signUp_input" ID="Regi_Password" type="password" runat="server" placeholder="**********" style="height: 20px; width: 90%; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Confirm Password</div>
<asp:TextBox CssClass="signUp_input" ID="Confirm_Regi_Password" type="password" runat="server" placeholder="**********" style="height: 20px; width: 90%; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Birth Date</div>
<asp:TextBox CssClass="signUp_input" ID="Age" type="number" runat="server" placeholder="dd/mm/yyyy" style="height: 20px; width: 90%; padding-left: 1px;"></asp:TextBox>
</div>
<div>
<div>Gender</div>
<asp:RadioButtonList CssClass="radio" ID="Gender" runat="server">
<asp:ListItem CssClass="radio" Value="1">Male</asp:ListItem>
<asp:ListItem CssClass="radio" Value="2">Female</asp:ListItem>
<asp:ListItem CssClass="radio" Value="3">Other</asp:ListItem>
</asp:RadioButtonList>
</br>
</div>
</div>
<asp:Button ID="Register_Button" runat="server" value="Join" OnClick="userRegister" CssClass="button_join" Text="Join" />
<asp:Label ID="Label1" CssClass="label" runat="server" Text=""></asp:Label>
</form>
I think the problem here is you are using the same SqlCommand that you have with the "insert" command to fill the data adapter (you don't change the command).
You can solve this three ways:
First one: Change the SqlCommand to a SELECT clause with the information you need to fill your session just before creating the DataAdapter.
Second one: Just fill your session with the form data like:
Session["user"] = Regi_Email.Text;
Session["user_name"] = First_Name.Text;
Of course you should handle the errors if the insert fails.
Third One: Use stored procedure so you can insert and fill the data adapter with a select in the same query.
IMHO i would prefer option 2 or 3.
Also i think you have to consider to have a better exception handling (Not all the errors that can actually happen are because the email is already in use) and you should consider using the "using" statement (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement) for disposing/closing the objects (SqlCommand and SqlDataAdapter).
Hope this helps.
I have to use multiple bootstrap carousel in single page, using the asp repeater control but it doesn't work, it just show one slider on the page
Here is the html and asp code
<div class="col-md-12">
<div id="Carousel" class="carousel slide">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="item">
<div class="row">
<asp:Repeater runat="server" ID="Slider1">
<ItemTemplate>
<div class="col-md-2">
<div class="row">
<a target="_blank" href="<%# Eval("URL") %>">
<img class="caption" src="../Includes/gaceta/<%# Eval("Titulo") %>/files/res/pages/page_0000.jpg" alt="<%# Eval("Titulo") %>" width="188" height="222" /></a>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<!--.row-->
</div>
</div>
<!--.carousel-inner-->
<a data-slide="prev" href="#Carousel" class="left carousel-control">‹</a>
<a data-slide="next" href="#Carousel" class="right carousel-control">›</a>
</div>
<!--.Carousel-->
</div>
<hr />
<div class="col-md-12">
<div id="Carousel2" class="carousel slide">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="item">
<div class="row">
<asp:Repeater runat="server" ID="Slider2">
<ItemTemplate>
<div class="col-md-2">
<div class="row">
<a target="_blank" href="<%# Eval("URL") %>">
<img class="caption" src="../Includes/gaceta/<%# Eval("Titulo") %>/files/res/pages/page_0000.jpg" alt="<%# Eval("Titulo") %>" width="188" height="222" /></a>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<!--.row-->
</div>
</div>
<!--.carousel-inner-->
<a data-slide="prev" href="#Folletos" class="left carousel-control">‹</a>
<a data-slide="next" href="#Folletos" class="right carousel-control">›</a>
</div>
<!--.Carousel-->
the javascript
$(document).ready(function () {
$('#Carousel').carousel('pause');
$('#Carousel2').carousel('pause');
$("div.item:first").addClass("active");
});
and the methods to bind the repeater
protected void Page_Load(object sender, EventArgs e)
{
BindSlider1(5);
BindSlider2(1);
}
protected void BindSlider1(int Ubicacion)
{
using (SqlConnection con = Conexion.Conecta())
{
using (SqlCommand cmd = new SqlCommand("SelGacetaUbicacion", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UBICACION", SqlDbType.Int).Value = Ubicacion;
con.Open();
Slider1.DataSource = cmd.ExecuteReader();
Slider1.DataBind();
}
}
}
protected void BindSlider2(int Ubicacion)
{
using (SqlConnection con = Conexion.Conecta())
{
using (SqlCommand cmd = new SqlCommand("SelGacetaUbicacion", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UBICACION", SqlDbType.Int).Value = Ubicacion;
con.Open();
Slider2.DataSource = cmd.ExecuteReader();
Slider2.DataBind();
}
}
}
I tried your code, and found this issues:
1- Review how to build the carousel markup depending on which version of bootstrap you are using. I tried with Bootstrap v3.1.0 and had to change parts of your markup. Refer to documentation or this sample.
For instance, <div class="item"> should be placed inside your repeater, and should have a <div class="container"> immediatly inside of it.
2- You are not initializing correctly both carousels from jquery, do something like this to correct it:
$("#Carousel div.item:first").addClass("active");
$("#Carousel2 div.item:first").addClass("active");
I have a repeater control inside a carousel which in turn is inside a modal.The problem is that the id of repeater control is not recogized or as it says id dosent exist in current context.
<div class="modal fade gallarymodal" id="mygallary" style=" width:1300px; height:100%;" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog mdialog">
<div class="modal-content" >
<div class="modal-body mbody">
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<asp:Repeater ID="repid" runat="server">
<ItemTemplate>
<div class="item" >
<div class="item active">
<asp:Image ID="wtf" runat="server" ImageUrl='<%#Eval("imgPath") %>' Width="1000px" Height="490px" />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</div>
</div>
</div>
</div>
And here is my .cs code
public void bindslide()
{
//string str = Session["userid"].ToString();
string str = "22";
sq.connection();
SqlCommand cmd = new SqlCommand("select * from mygallary where regId_img='" + str + "' ", sq.con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
//DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
//da.Fill(ds);
if (dt.Rows.Count > 0)
{
repid.DataSource = dt;
repid.DataBind();
sq.con.Dispose();
sq.con.Close();
}
else
{
}
}
I am very much confused why the id repeater control is not recognized.
asp:Repeater ID="wtf"
asp:Image ID="wtf"
maybe the problem both got same id .
try change the id of one of them .
one closing tag on div missing