TextBox.Text Updated On DropDownList_TextChanged - c#

I have a DropDownList connected with an sqlDataSource and a TextBox .
I want every time the user selects a name from the column name listed on the DropDownList,
the value of the column id of that item being displayed on the text of the TextBox
I made this code but doesnt seems to work:
(the code contains no errors)
protected void DropDownListIliaka_SelectedIndexChanged(object sender, EventArgs e)
{
string conString = "Data Source=icsd-db.aegean.gr\\icsdmssqlsrv;Initial Catalog=icsd12015;Integrated Security=True;";
SqlConnection con = new SqlConnection(conString);
string cmdText = "SELECT iliako_sistima_ID FROM iliako_sistima WHERE name = '" + DropDownListIliaka.Text + "'";
SqlCommand cmd = new SqlCommand(cmdText, con);
try
{
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
iliako_sistima_id.Text = (reader["Iliako_Sistima_ID"].ToString());
}
}
}
finally
{
con.Close();
}
}

this
string cmdText = "SELECT iliako_sistima_ID FROM iliako_sistima WHERE name = '" + DropDownListIliaka.Text + "'";
should be
string cmdText = "SELECT iliako_sistima_ID FROM iliako_sistima WHERE name = '" + DropDownListIliaka.SelectedItem.Text + "'";
Hope this helps

You must set the property AutoPostBack of DropDownList to true, so it posts back to the server and sets the value of textbox

Related

Connection is not closed properly ASP.NET C#

I have this button click event. Been trying to replace the con.Close() in different lines of code, tried for hours but couldn't fix. Maybe a second pair of eyes can help?
Error: System.InvalidOperationException: 'The connection was not closed. The connection's current state is open.'
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
con.Open();
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
con.Close();
}
else
{
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
con.Open();
int i = cmd1.ExecuteNonQuery();
con.Close();
if (i != 0)
{
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
}
else
{
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
}
Try this (open connection only once and close only once):
protected void Button1_Click(object sender, EventArgs e) {
using(SqlConnection con = new SqlConnection()) {
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
bool hasRows = reader.HasRows;
reader.Close();
if (hasRows) {
// This line makes no sense after the execution of the query.
//cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
} else {
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
int i = cmd1.ExecuteNonQuery();
if (i != 0) {
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
} else {
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
con.Close();
}
}
Now let's discuss this line
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
This let's attacker manipulate your input with sql injection. To solve this, use the same cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value); that you are using in the second query. The Session["id"] is somewhat safer as it is not provided by the user but better safe than sorry as the parameters sanitize the input and protect you from sql injection.

prevent duplicate data from Excel to db via Oledb c#

I Have a excel and I want Upload only four columns of that to SQL Table with a button.
The problem is when I repeat click the button all of that data will be duplicated but I Don't want that. I want only new data to be update.
My query:
protected void Button1_Click(object sender, EventArgs e)
{
int UserID;
int InsuID;
string Result;
int Year;
//** مسیر فایل اکسل**
String ExcelPath = #"D:\Insu_lab.xlsx";
//** کانکشن به آفیس**
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
UserID = Convert.ToInt32(dr[0].ToString());
InsuID = Convert.ToInt32(dr[1].ToString());
Result = dr[2].ToString();
Year = Convert.ToInt32(dr[3].ToString());
savedata(UserID, InsuID, Result, Year);
Label1.Text = "اطلاعات با موفقیت در دیتابیس ذخیره شد";
}
}
private void savedata(int UserID, int InsuID, string Result, int Year)
{
String query = "insert into tbl_Result(UserID,InsuID,Result,Year) values(" + UserID + ",'" + InsuID + "','" + Result + "','" + Year + "') ";
String mycon = "Data Source=MC6082; Initial Catalog=Insurance; Integrated Security=true";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
Solution 1: When you clickedon button, that(button) disable the button.
Button1.disable = true;
When export ended:
Button1.disable = false;
Solution 2: you can use from jquery ajax in this part.

Error in gridviewUpdating asp.net with a timestamp update

I have two buttons, SetIn and SetOut. They both have the commandName UPDATE ( I have two buttons as I'd like the text to be different on the button depending on the value of one field in the row.
I'm getting a problem in that when I run the update SQL statement, it throws an error at me. It says:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '14'.
This means that there is an issue with the date and time stamp that I am trying to update the row with (I'm making the update at 14.02pm).
My aspx.cs page code is:
protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_Index") as Label;
int rowToUpdate = Int32.Parse(id.Text);
con = new SqlConnection(cs);
int scopeValue;
con = new SqlConnection(cs);
cmd = new SqlCommand();
cmd.CommandText = "SELECT in_scope FROM " + databaseName + " WHERE id = '" + rowToUpdate + "'";
cmd.Parameters.AddWithValue("#id", rowToUpdate);
cmd.Connection = con;
try
{
con.Open();
scopeValue = Convert.ToInt32(cmd.ExecuteScalar());
//database_entries.Text = recordCount.ToString();
}
finally
{
con.Close();
}
string modifiedBy = userManagement.getWeldID();
string updateDate = DateTime.UtcNow.ToString("dd/MMM/yyyy HH:mm:ss");
{
if (scopeValue == 1)
{
// Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_Index") as Label;
string sqlStatement = "";
con = new SqlConnection(cs);
// SqlCommand cmd = new SqlCommand();
sqlStatement = #"update dbo.Fair_Use_InScope_MIF_Alex_temp set in_scope = '0', modified_by = " + modifiedBy + ", date_updated = " + updateDate + " where id = '" + rowToUpdate + "'";
con.Open();
cmd = new SqlCommand(sqlStatement, con);
cmd.ExecuteNonQuery();
con.Close();
ShowData();
}
if (scopeValue == 0)
{
// Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_Index") as Label;
string sqlStatement = "";
con = new SqlConnection(cs);
// SqlCommand cmd = new SqlCommand();
sqlStatement = #"update dbo.Fair_Use_InScope_MIF_Alex_temp set in_scope = '1', modified_by = " + modifiedBy + ", date_updated = " + updateDate + " where id = '" + rowToUpdate + "'";
con.Open();
cmd = new SqlCommand(sqlStatement, con);
cmd.ExecuteNonQuery();
con.Close();
ShowData();
}
}
}
I'm basically trying to get the scopeValue (0 or 1) of the row, and if the Update command is called, and the scopeValue was previously 0, set it to 1 now and vice versa. I also need to update the time that the change was made and who made the change in that row. (these are both displayed in the gridview)
Any help would be much appreciated as I am a beginner to ASP.NET and C# and SQL SERVER!!
You are sending a DateTime as a string (without even enclosing single quotes date_updated = '" + updateDate + "') and that will always cause problems.
It's better to use parameters in your query. This prevents SQL injection, improves readability, ensures type safety, no more worries about the correct use of quotation marks etc.
string sqlStatement = "UPDATE dbo.Fair_Use_InScope_MIF_Alex_temp SET in_scope = 0, modified_by = #modifiedBy, date_updated = #updateDate WHERE (id = #rowToUpdate)";
using (SqlConnection connection = new SqlConnection(cs))
using (SqlCommand command = new SqlCommand(sqlStatement, connection))
{
command.Parameters.Add("#modifiedBy", SqlDbType.VarChar).Value = modifiedBy;
command.Parameters.Add("#updateDate", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#rowToUpdate", SqlDbType.Int).Value = 35;
connection.Open();
command.ExecuteNonQuery();
}

Connect to two tables

I have created comboBox and filled with one column, after I choose item from the combobox I would like to show other column in the textboxs so I wrote code to make it happen but what if I want to choose column from another table I mean I would like to show couple of columns from two different table in the textbox when I hit the combobox
Here is my code:
private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*******";
string Query = "select * from rmsmasterdbtest.dbo.customer where LastName= '" + comboLname.Text + "' ;";
SqlConnection Myconn = new SqlConnection(conn);
SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
SqlDataReader Reader;
try
{
Myconn.Open();
Reader = cmdDataBase.ExecuteReader();
while (Reader.Read())
{
string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber"));
//string Time = Reader.GetString(Reader.GetOrdinal("Time"));
// string Deposit = Reader.GetString(Reader.GetOrdinal("Deposit"));
string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
txtid.Text = ID;
txtacnum.Text = AccountNuber;
//txttime.Text = Time;
//txtdeposit.Text = Deposit;
txtstatus.Text = sstatus;
txtlname.Text = slastname;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Myconn.Close();
}
}

Populate gridview from listbox such that first few rows become columns in gridview

protected void Button1_Click(object sender, EventArgs e)
{
string sqlstring;
OleDbConnection connection = new OleDbConnection("Provider=MSDAORA;Data Source=solaris;Password=medical;User ID=medical");
sqlstring = "select emp_name,decode(sex,null,null,'Self')rel,decode(dob,null,'Ad',floor(months_between(sysdate,dob)/12))age,decode(f_elg,'Y',f_name,null) f_name,decode(f_elg,'Y','Father',null) f_rel,decode(f_dob,null,'Ad',floor(months_between(sysdate,f_dob)/12)) f_age,decode(m_elg,'Y',m_name,null) m_name,decode(m_elg,'Y','Mother',null) m_rel,decode(m_dob,null,'Ad',floor(months_between(sysdate,m_dob)/12)) m_age,decode(s_elg,'Y',s_name,null) s_name,decode(s_elg,'Y',decode(s_sex,'M','Husband','F','Wife'),null) s_rel,decode(s_dob,null,'Ad',floor(months_between(sysdate,s_dob)/12)) s_age,decode(dep_elg1,'Y',dep_name1,null) dep_name1,decode(dep_sex1,'M','Son','F','Daughter',null) dep_rel1,decode(dep_dob1,null,null,floor(months_between(sysdate,dep_dob1)/12)) dep_age1,decode(dep_elg2,'Y',dep_name2,null) dep_name2,decode(dep_sex2,'M','Son','F','Daughter',null) dep_rel2,decode(dep_dob2,null,null,floor(months_between(sysdate,dep_dob2)/12)) dep_age2,decode(dep_elg3,'Y',dep_name3,null) dep_name3,decode(dep_sex3,'M','Son','F','Daughter',null) dep_rel3,decode(dep_dob3,null,null,floor(months_between(sysdate,dep_dob3)/12)) dep_age3,decode(dep_elg4,'Y',dep_name4,null) dep_name4,decode(dep_sex4,'M','Son','F','Daughter',null) dep_rel4,decode(dep_dob4,null,null,floor(months_between(sysdate,dep_dob4)/12)) dep_age4,decode(dep_elg5,'Y',dep_name5,null) dep_name5,decode(dep_sex5,'M','Son','F','Daughter',null) dep_rel5,decode(dep_dob5,null,null,floor(months_between(sysdate,dep_dob5)/12)) dep_age5,decode(dep_elg6,'Y',dep_name6,null) dep_name6,decode(dep_sex6,'M','Son','F','Daughter',null) dep_rel6,decode(dep_dob6,null,null,floor(months_between(sysdate,dep_dob6)/12)) dep_age6 from employee_mas where emp_no='" + TextBox1.Text + "'";
//sqlstring = "select COALESCE(emp_name,'') + ' ' + COALESCE(sex,'')as empinfo from employee_mas where emp_no='" + TextBox1.Text + "'";
OleDbCommand comm = new OleDbCommand(sqlstring, connection);
OleDbDataReader reader;
connection.Open();
reader = comm.ExecuteReader();
if (reader.Read())
{
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("emp_name")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("age")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("rel")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_name")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_age")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_rel")));
}
}
This is the code I have used to populate my listbox
Now I want that my gridview which is having 3 columns such as:
Name Age Rel
so first 3 values be inserted in the first row of the gridview
second 3 in the second and so on.
An help will be great.
You can use a DataTable to store the rows and then after reading all the records, you bind it to the GridView:
protected void Button1_Click(object sender, EventArgs e)
{
string sqlstring;
OleDbConnection connection = new OleDbConnection("Provider=MSDAORA;Data Source=solaris;Password=medical;User ID=medical");
sqlstring = "select emp_name,decode(sex,null,null,'Self')rel,decode(dob,null,'Ad',floor(months_between(sysdate,dob)/12))age,decode(f_elg,'Y',f_name,null) f_name,decode(f_elg,'Y','Father',null) f_rel,decode(f_dob,null,'Ad',floor(months_between(sysdate,f_dob)/12)) f_age,decode(m_elg,'Y',m_name,null) m_name,decode(m_elg,'Y','Mother',null) m_rel,decode(m_dob,null,'Ad',floor(months_between(sysdate,m_dob)/12)) m_age,decode(s_elg,'Y',s_name,null) s_name,decode(s_elg,'Y',decode(s_sex,'M','Husband','F','Wife'),null) s_rel,decode(s_dob,null,'Ad',floor(months_between(sysdate,s_dob)/12)) s_age,decode(dep_elg1,'Y',dep_name1,null) dep_name1,decode(dep_sex1,'M','Son','F','Daughter',null) dep_rel1,decode(dep_dob1,null,null,floor(months_between(sysdate,dep_dob1)/12)) dep_age1,decode(dep_elg2,'Y',dep_name2,null) dep_name2,decode(dep_sex2,'M','Son','F','Daughter',null) dep_rel2,decode(dep_dob2,null,null,floor(months_between(sysdate,dep_dob2)/12)) dep_age2,decode(dep_elg3,'Y',dep_name3,null) dep_name3,decode(dep_sex3,'M','Son','F','Daughter',null) dep_rel3,decode(dep_dob3,null,null,floor(months_between(sysdate,dep_dob3)/12)) dep_age3,decode(dep_elg4,'Y',dep_name4,null) dep_name4,decode(dep_sex4,'M','Son','F','Daughter',null) dep_rel4,decode(dep_dob4,null,null,floor(months_between(sysdate,dep_dob4)/12)) dep_age4,decode(dep_elg5,'Y',dep_name5,null) dep_name5,decode(dep_sex5,'M','Son','F','Daughter',null) dep_rel5,decode(dep_dob5,null,null,floor(months_between(sysdate,dep_dob5)/12)) dep_age5,decode(dep_elg6,'Y',dep_name6,null) dep_name6,decode(dep_sex6,'M','Son','F','Daughter',null) dep_rel6,decode(dep_dob6,null,null,floor(months_between(sysdate,dep_dob6)/12)) dep_age6 from employee_mas where emp_no='" + TextBox1.Text + "'";
//sqlstring = "select COALESCE(emp_name,'') + ' ' + COALESCE(sex,'')as empinfo from employee_mas where emp_no='" + TextBox1.Text + "'";
OleDbCommand comm = new OleDbCommand(sqlstring, connection);
OleDbDataReader reader;
connection.Open();
DataTable table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Age");
table.Columns.Add("Rel");
reader = comm.ExecuteReader();
if (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("emp_name"));
string age = reader.GetString(reader.GetOrdinal("age"));
string rel = reader.GetString(reader.GetOrdinal("rel"));
ListBox1.Items.Add(name);
ListBox1.Items.Add(age);
ListBox1.Items.Add(rel);
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_name")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_age")));
ListBox1.Items.Add(reader.GetString(reader.GetOrdinal("f_rel")));
table.Rows.Add(name, age, rel);
}
GridView.DataSource = table;
GridView.DataBind();
}

Categories