Accessing code behind method Variable in aspx page - c#

I am working in custom detailed view. I have a program page that views all the program. When a user clicks on update button, the user is redirected to manage programs page. The Manage Programs Page contains a method that fetches all the rows from.
public string ProgramsDetails()
{
using (SqlConnection con = new SqlConnection(str))
{
string htmlStr = "";
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = " SELECT * from programs where ProgId=#ProgId";
cmd.Parameters.AddWithValue("#ProgId", "1");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
int ProgId = reader.GetInt32(0);
string ProgTitle = reader.GetString(1);
string ProgBudget = reader.GetString(4);
string ProgStarDate = reader.GetString(5);
}
con.Close();
return htmlStr;
}
}
How can I access a variable from .aspx page? Lets say I would like to access ProgTitle.
I have used this method but seems it's not working
<%=ProjTitle%>
I would like to show the values of each column in there respected text box
<div class="cmrs-panel-body no-padding">
<div class="cmrs-form-inline">
<div class="cmrs-form-row bordered">
<label class="cmrs-form-label">Program Code Name</label>
<div class="cmrs-form-item">
<input type="text" name="Code" class="large">
</div>
</div>
</div>
<div class="cmrs-form-inline">
<div class="cmrs-form-row bordered">
<label class="cmrs-form-label">Program Title</label>
<div class="cmrs-form-item">
<input type="text" name="Title" class="large" value="<%=ProgTitle %>">
</div>
</div>
</div>
<div class="cmrs-form-inline">
<div class="cmrs-form-row bordered">
<label class="cmrs-form-label">Program Description</label>
<div class="cmrs-form-item">
<textarea class="large"></textarea>
</div>
</div>
</div>
</div>
Normally i would add the html code to method but this is not feasible so i want to get the variable value and display it in textbox.
htmlStr+="<table><tr><td>"+ProgTitle+"</td></tr></table>";

ProgTitle must be declared as protected or public in the code behind to make it accessible from .aspx. Change your code as below
protected string ProgTitle;
public string ProgramsDetails()
{
using (SqlConnection con = new SqlConnection(str))
{
string htmlStr = "";
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = " SELECT * from programs where ProgId=#ProgId";
cmd.Parameters.AddWithValue("#ProgId", "1");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
int ProgId = reader.GetInt32(0);
ProgTitle = reader.GetString(1);
string ProgBudget = reader.GetString(4);
string ProgStarDate = reader.GetString(5);
}
con.Close();
return htmlStr;
}
}
then you can access ProgTitle in your aspx code
<input type="text" name="Title" class="large" value="<%=ProgTitle %>">

If not using databinding, how about using session and allocate the variable then use it. On code Behing: SESSION.START(); SESSION["PjTitle"]=PrgTtile;
and then in aspx acces it with: <%= SESSION["PjTitle"] %>

Related

I can't update content from CKEditor to sql server (use asp.net web form)

I use asp.net web form to make a website.
Then I install CKEditor and can insert content into sql server.
However I'd like to use CKEditor to update data in database is failed.
This is my aspx code
<%# Page Title="" Language="C#" MasterPageFile="~/admin/admin.Master" AutoEventWireup="true" CodeBehind="AboutUsContent.aspx.cs" Inherits="yacht.admin.AboutUsContent" %>
<%# Register assembly="CKEditor.NET" namespace="CKEditor.NET" tagprefix="CKEditor" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<!-- [ Main Content ] start -->
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-header">
<h5>Update About Us Content</h5>
</div>
<div>
<CKEditor:CKEditorControl ID="CKEditorControl2" runat="server" BasePath="/Scripts/ckeditor/" Toolbar="Bold|Italic|Underline|Strike|Subscript|Superscript|-|RemoveFormat
NumberedList|BulletedList|-|Outdent|Indent|-|JustifyLeft|JustifyCenter|JustifyRight|JustifyBlock|-|BidiLtr|BidiRtl
/
Styles|Format|Font|FontSize
TextColor|BGColor
Link|Image">
</CKEditor:CKEditorControl>
</div>
<br/>
<div style="margin:auto;">
<asp:Button ID="SubmitBTN" runat="server" Text="Submit" OnClick="SubmitBTN_Click" class="btn btn-secondary btn-sm" />
</div>
</div>
</div>
</div>
<!-- [ Main Content ] end -->
</asp:Content>
This is my aspx.cs code
namespace yacht.admin
{
public partial class AboutUsContent : System.Web.UI.Page
{
string getsql = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["yachtConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
FileBrowser fileBrowser = new FileBrowser();
fileBrowser.BasePath = "/ckfinder";
fileBrowser.SetupCKEditor(CKEditorControl2);
SqlConnection connection = new SqlConnection(getsql);
string sql = "SELECT AboutUsContent FROM AboutUs WHERE id = 1";
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
CKEditorControl2.Text = HttpUtility.HtmlDecode(reader["AboutUsContent"].ToString());
}
connection.Close();
}
protected void SubmitBTN_Click(object sender, EventArgs e)
{
string aboutUs = HttpUtility.HtmlEncode(CKEditorControl2.Text);
DateTime getdate = DateTime.Now;
string dateNow = getdate.ToString("yyyy-MM-dd HH:mm:ss");
SqlConnection connection = new SqlConnection(getsql);
string sql = "UPDATE AboutUs SET AboutUsContent = #AboutUsContent, LastMotifiedDate = #LastMotifiedDate WHERE id = 1";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#AboutUsContent", aboutUs);
command.Parameters.AddWithValue("#LastMotifiedDate", dateNow);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Response.Redirect("AboutUs");
}
}
}
When I edited content in CKEditor, it couldn't update to sql server
(It can't grab CKEditor's content)
I tried it for whole day, what can I do now....
Thanks first for all of you.

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.

Trying to insert data into MS Access database using C# but insert command is not working

I am getting an error with my insert command. I am trying to add the users input data from the text boxes on the html page into the access database I already have created and connected. I am just having a problem with the syntax of my insert command.
This is my HTML page
<form name="insert" method="post" action="insertinventory.aspx">
<center>
<h1> FLOATEEZ Add Inventory </h1>
Item Number: <input type="text" name="txtnum"> <br>
Item Name: <input type="text" name="txtname"> <br>
Item Description: <input type="text" name="txtdescription"> <br>
Item Price: <input type="text" name="txtprice"> <br>
Item Quantity on Hand: <input type="text" name="txtqoh"> <br>
Item Picture: (text only) <input type="text" name="txtpicture"> <br><br>
<input type="submit" value="Submit"> &nbsp &nbsp <input type="reset">
</center>
</form>
This is my aspx page minus my database information
<%# Page Language="C#" Debug="true" %>
<%# Import Namespace="System.Data.Odbc" %>
<%
Response.Write("<html><head><title>Insert into Inventory </title></head></body>");
Response.Write("<body bgcolor=lightblue>");
OdbcConnection myconn;
OdbcCommand mycmd;
OdbcDataReader myreader;
myconn= new OdbcConnection( I removed this part );
mycmd = new OdbcCommand("insert into inventory
(Itemnum,Itemname,Itemdescription,Itemprice,Itemqoh,Itempicture) values
('"+ txtnum.Text +"','"+ txtname.Text +"','"+ txtdescription.Text
+"','"+ txtprice.Text +"','"+ txtqoh.Text +"','"+ txtpicture.Text
+"')",myconn);
myreader.Close();
myconn.Close();
%>
<br>
<center> <a href ="Company.html" > Back to our Homepage </a> </center>
be sure to use parameters! a question mark is used for each value you get from the user.
example below taken from https://www.mikesdotnetting.com/article/26/parameter-queries-in-asp-net-with-ms-access. (a great resource.)
string ConnString = Utils.GetConnString();
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
You need to bind the connection to command, and call command execution statement, e.g.:
...
mycmd.Connection = myconn;
mycmd.ExecuteNonQuery();
myconn.Close();
No reader needed.
The better way to operate the DB is:
using(OdbcConnection myconn = new OdbcConnection(connectionString))
{
using(OdbcCommand mycmd = OdbcCommand(your code here))
{
mycmd.Connection = myconn;
mycmd.ExecuteNonQuery();
}
}
For using keyword, it will be disposing the connection and command instance automatically.

asp.net image src not showing from database in listview

I am facing very rear problem. I am trying to bind images path from database using listview control. Listview gets bind but img is not showing up. When I look at inspect I cant's see src attribute in img tag. Listview gets bind perfectly and path is also correct. If you see below screenshot & see the highlighted line which is that img tag which is missing src attribute.
<div class="row">
<asp:ListView ID="subCategoriesList" runat="server">
<ItemTemplate>
<div class="col-md-3">
<img id="myimag" runat="server" src='<%# Eval("icon") %>' />
<br /><%# Eval("name") %>
</div>
</ItemTemplate>
</asp:ListView>
</div>
ListviewBind Code
private void bindSubCatgoriesRightSide()
{
try {
string constr = ConfigurationManager.ConnectionStrings("conio2").ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr)) {
using (MySqlCommand cmd = new MySqlCommand()) {
cmd.CommandText = "SELECT * FROM subcategory WHERE type = 'product' and category = 'mobile' and status = 'active'";
cmd.Connection = con;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd)) {
DataTable dt = new DataTable();
sda.Fill(dt);
subCategoriesList.DataSource = dt;
subCategoriesList.DataBind();
}
}
}
} catch (Exception ex) {
Response.Write(ex);
}
}
I think you're looking at the wrong output section, in your listview item template, you are wrapping the image in <div class="col-md-3"></div ...
but in the screenshot, the image is wrapped in <div class="col-md-6 col-sm-6 col-xs-12 margin-bottom"></div
Unless you are changing the classes with JS

After some idle time images not load from database

My problem is when I click on the product page (in URL below). It works good but after some idle time on first click on product menu it wont load product images from database to Repeater control.
I am using Bootstrap and not using update-panel.
Please Refer Below Link.
MySite(See Product Page On First Time And Click After 5 to 10 minute of idle time)
My ASP.net code is
<asp:Repeater ID="rptrProduct" runat="server">
<ItemTemplate>
<div class="portfolio-item col-xs-12 col-sm-4 col-md-3">
<div class="recent-work-wrap hovereffect">
<img id="dtimg1" runat="server" class="img-responsive imggray" src='<%#Eval("ImagePath")%>' alt="" style="height: 185px!Important;" />
<div class="overlay1">
<div class="recent-work-inner">
<a id="aimg2" runat="server" href='<%#Eval("ImagePath")%>' rel="prettyPhoto">
<h2>
<%#Eval("ProductName")%></h2>
</a>
<p>
<a id="adtimg1" runat="server" class="preview" href='<%# string.Format("~/BMSubProduct.aspx?pro={0}", Eval("ProductId")) %>'>
<i class="fa fa-eye"></i>View Products</a>
</p>
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I am just not getting that why on first time it won't load any images.
my C# page code is
if(!Page.IsPostBack)
{
DataTable dt = DBMaster.getQueryDataTableSchema(query);
if (dt.Rows.Count > 0)
{
string path = GlobalFunction.getPath(1);
NoProducts.Visible = false;
for (int i = 0; i < dt.Rows.Count; i++)
dt.Rows[i]["ImagePath"] = path + Convert.ToString(dt.Rows[i] ["ImagePath"]);
rptrProduct.DataSource = dt;
rptrProduct.DataBind();
}
else
{
NoProducts.Visible = true;
rptrProduct.DataSource = null;
rptrProduct.DataBind();
}
}
public static DataTable getQueryDataTableSchema(string query)
{
try
{
using (IDbConnection con = sq.Open())
{
IDbCommand cmd = con.CreateCommand();
cmd.CommandText = query;
IDbDataAdapter adp = sq.GetAdapter(cmd);
DataSet ds = new DataSet();
adp.FillSchema(ds, SchemaType.Source);
adp.Fill(ds);
con.Close();
return ds.Tables[0];
}
}
catch (Exception ex)
{
return new DataTable();
}
}
and masterpage code in page_load is
if (!Page.IsPostBack)
{
SQLString.Config = myconnectionString;
}
Here NoProduct => No Products Are Available Right Now.
I have tried many things like below:
EnableViewState="true" And EnableViewState="false" both for repeater and in page also.
Change connection string in web.config like
name="SQLConStr" connectionString="Server=localhost;Database=databasename; Uid = username; Pwd = password; Pooling = false; Connection Timeout = 30"
Here tried with and without connection timeout and pooling.
Note: Using MySQL database and using interface to open database connection.
Thanks in advance.
EnableViewState="true"
and try to use
<asp:Image and <asp:HyperLink controls
instead of
img and a tags with runat="server".

Categories