dropdownlist Insert always the default value - asp.net

I have one dropdownlist with data from database table and i want do insert with this ddl + 2 texbox field in another table . The insert work but always insert the default dropdownList witch displays first. wHat am i missing?
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = cs.getConnection();
string query = "SELECT Id, NAME FROM PROFITCATEGORIES";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
using (SqlDataReader rdr = command.ExecuteReader())
{
DropDownListCategory.DataSource = rdr;
DropDownListCategory.DataTextField = "Name";
DropDownListCategory.DataValueField = "ID";
DropDownListCategory.DataBind();
}
}
}
protected void ButtonSave_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(TextBoxValue.Text))
return;
string connectionString = cs.getConnection();
string insertSql = "INSERT INTO profits(Value,DateCreate,IdCategory,IdUser) VALUES(#Value, #DateCreate,#CategoryId,#UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(insertSql, myConnection);
//параметризация се прави тук за да се избегне SQL Injection
command.Parameters.AddWithValue("#Value", TextBoxValue.Text);
command.Parameters.AddWithValue("#DateCreate", TextBoxData.Text);
command.Parameters.AddWithValue("#CategoryId", DropDownListCategory.SelectedValue);
command.Parameters.AddWithValue("#UserId", cui.getCurrentId());
command.ExecuteNonQuery();
//пренасочваме заявката към същата страница за да се видят новите резултати и да се избегне проблем с дублиране на инсерт при рефреш на страницата
Response.Redirect("~/Profit.aspx");
myConnection.Close();
}
TextBoxValue.Text = string.Empty;
}

You're re-binding the list on every page load. Wrap the data-binding code in an if (!IsPostBack) block.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Bind the list here...
}
}

Everytime you press the asp:button the page gets reloaded, and the code in the page_load method gets initialised again. That's why the default item is always inserted in your database.
Put this around your code in the page_load: (if (!Page.IsPostback))
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.isPostback)
{
string connectionString = cs.getConnection();
string query = "SELECT Id, NAME FROM PROFITCATEGORIES";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
using (SqlDataReader rdr = command.ExecuteReader())
{
DropDownListCategory.DataSource = rdr;
DropDownListCategory.DataTextField = "Name";
DropDownListCategory.DataValueField = "ID";
DropDownListCategory.DataBind();
}
}
}
}

Use the AppendDataBoundItems property and set it to true, and only bind on PostBack:
How Do I Add an Additional Item To a Databound DropDownList Control in ASP.NET?
ListControl.AppendDataBoundItems Property

Related

Display Image from folder while the path is in Database In RDLC Report ASP.Net MVC5

How to show pictures which are located in a folder and the path is in the database But I'm unable to Do it.
testingDataSet RTP = new testingDataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/RTPrpt.rdlc");
FillRTP();
ReportDataSource dataSource = new ReportDataSource("DataSetRTP", RTP.Tables["RTPView"]);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(dataSource);
ReportViewer1.LocalReport.Refresh();
}
private void FillRTP()
{
string connectionString = Properties.Settings.Default.ETHADAIMS;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
string queryString = string.Empty;
queryString = " select * from RTPView";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(queryString, sqlConnection);
sqlDataAdapter.Fill(RTP, RTP.Tables["RTPView"].TableName);
}
}
}
enter image description here
Photos are not visible. How can I make them to be visible?

How to get a table on a new web page when a button is Clicked

This is my one tag:
<asp:Button ID="button" runat="server" Text="ShowOrder" onclick="newTab" />
This is my 'aspx.cs' which will be called when button is clicked
protected void newTab(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?id="+txtSearchCustomerByID.Value);
}
What I want is to print my sql table on loaded web tab (new page) when it gets loaded.
My stored procedure is displaying the data of my table where id is equal to "id entered by user in textbox".
Now,
protected void Page_Load(object sender, EventArgs e)
{
int id_no = int.Parse(Request.QueryString["id"]);
if (Page.IsPostBack)
{
showOrders(id_no);
}
}
Now what should I have in 'Default2.aspx' so that I will get my table by using,
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand("showOrdersSP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
con.Open();
.......
}
}
I need to use DataTable
So simply when I clicked, I will get data table on new page
You can refer below code:
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
DataTable dt = new DataTable();
SqlParameter[] p1 = new SqlParameter[1];
p1[0] = new SqlParameter("#id", id);
dt= getRecords_table("showOrdersSP", p1); // you will get your DataTable here
}
}
// Common Method for FillYour Tables
private DataTable getRecords_table(string spname, SqlParameter[] para)
{
string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["connName"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connectionstring);
SqlDataAdapter ad = new SqlDataAdapter(spname, con);
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
ad.SelectCommand.Parameters.AddRange(para);
con.Open();
ad.Fill(dt);
con.Close();
return dt;
}
Hope it will helps you
Thanks

Gridview doesn't refresh after deleting a row

I have a GridView in an UpdatePanel.
When I add a row, it gets updated right away. The problem is that, when I delete a row, it doesn't update the GridView.
What can be done?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["EventId"] != null)
{
ExtractEventData();
GridView1.DataSourceID = "SqlDataSource1";
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string CS =
ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spInsertComment", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Comment", txtComment.Text);
cmd.Parameters.AddWithValue("#Eventid", lblEventId.Text);
cmd.Parameters.AddWithValue("#UserId", Session["UserId"].ToString());
cmd.ExecuteNonQuery();
txtComment.Text = "";
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = Int32.Parse(e.CommandArgument.ToString());
string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand(
"Delete from tblEventComments WHERE CommentId = #CommentId", con);
cmd.Parameters.AddWithValue("#CommentId", id);
cmd.ExecuteNonQuery();
GridView1.DataSourceID = "";
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
}
I have also tried removing the datasource1 connection from GridView and then re-assigned it. Still it doesn't seem to work, the way I need it to.
I don't think you will need the GridView markup here, however you can ask for it if necessary.
According to this post, you should delete the row using GridView.DeleteRow method.

lable is not showing any output for the dropdown list selection

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LibraryConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlbookavail.Items.Add(new ListItem("select", "-1"));
ddlbookavail.AppendDataBoundItems = true;
SqlCommand cmd = new SqlCommand("select * from tblbookinfo", con);
con.Open();
ddlbookavail.DataSource = cmd.ExecuteReader();
ddlbookavail.DataTextField = "Name";
ddlbookavail.DataValueField = "Id";
ddlbookavail.DataBind();
con.Close();
txtdate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
}
in my design page i put the sql datasource from data and got this connection srting

The ConnectionString property has not been initialized

My connection string is placed in web.config as follows.
<connectionStrings>
<add name="empcon" connectionString="Persist Security Info=False;User ID=sa;Password=abc;Initial Catalog=db5pmto8pm;Data Source=SOWMYA-3BBF60D0\SOWMYA" />
</connectionStrings>
and the code of program is...
public partial class empoperations : System.Web.UI.Page
{
string constr = null;
protected void Page_Load(object sender, EventArgs e)
{
ConfigurationManager.ConnectionStrings["empcon"].ToString();
if (!this.IsPostBack)
{
fillemps();
}
}
public void fillemps()
{
dlstemps.Items.Clear();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["empcon"].ConnectionString);
con.ConnectionString = constr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from emp";
cmd.Connection = con;
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem lt = new ListItem();
lt.Text = reader["ename"].ToString();
lt.Value = reader["empno"].ToString();
dlstemps.Items.Add(lt);
}
reader.Close();
}
catch (Exception er)
{
lblerror.Text = er.Message;
}
finally
{
con.Close();
}
i am totally new to programing....
i am able to run this application with er.message in label control as "the connection string property has not been initialized"
i need to retrieve the list of names of employees from the emp table in database into the dropdownlist and show them to the user...
can any one please fix it...
Where are you initializing your constr variable? It looks like you can leave that line out.
Also: just use using
using(SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["empcon"].ConnectionString)
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
//Rest of your code here
}
}
Side note: Don't use Select * From. Call out your columns: Select empname, empno From...
You are not assigning ConfigurationManager.ConnectionStrings["empcon"].ToString(); to string constr
protected void Page_Load(object sender, EventArgs e)
{
constr = ConfigurationManager.ConnectionStrings["empcon"].ToString();
...
will probably solve your problem for the time being.

Resources