Update Checkboxlist to database in asp.net C# - asp.net

I want to update multi checkboxlist value to the the database. I already databound my checkboxlist from other table which is the medicine table. Now i want to update my value to consultation table, but i can not
`
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < txtcheckbox.Items.Count - 1; i++)
{
if (txtcheckbox.Items[i].Selected == true)
{
str = str + txtcheckbox.Items[i].Text + ",";
}
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
String sql = "UPDATE [consultation] set mname3 = " + str + " WHERE [conid] = #conid";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#conid", txtconid);
cmd.Parameters.AddWithValue("#mname3", str);
int j = cmd.ExecuteNonQuery();
if (j > 0)
{
Label2.Visible = true;
Label2.Text = "Successfully Complete Dispensary";
txtconid.Text = "";
}
else
{
Label2.Visible = true;
Label2.Text = "Not Successfully Complete Dispensary";
txtconid.Text = "";
}
con.Close();
}
catch
{
Label2.Visible = true;
Label2.Text = "Error";
txtconid.Text = "";
}
}
`

I guess you have exception here. Because:
String sql = "UPDATE [consultation] set mname3 = " + str + " WHERE [conid] = #conid";
here you use concatenation of strings and your sql query will look like:
UPDATE [consultation] set mname3 = sometextvale WHERE [conid] = #conid
mname3 have nvarchar sql type I guess, so you need to put string value in qoutes:
String sql = "UPDATE [consultation] set mname3 = ' " + str + " ' WHERE [conid] = #conid";
Or you can use paramaeter for sql query, like you already did for #conid:
String sql = "UPDATE [consultation] set mname3 = #mname3 WHERE [conid] = #conid";
It's better solution in security way.
Some additional comments:
for (int i = 0; i < txtcheckbox.Items.Count - 1; i++)
Are you sure here should be txtcheckbox.Items.Count - 1? You will lost the last one.
And the 2nd one: Mix code for construction and execution query (DAL) in code behind of page with some kind of business logic not a good practice =)

Related

sqldatasource select command didn't work

I have a problem doing search in asp.net, when I try to run the code in sqlserver or using query buider it works fine. But when I run the program in browser, the gridview didn't even show up. Help plz.
protected void btnsearchadvance_Click(object sender, EventArgs e)
{
if (txtname.Text.Trim() != "")
{
search = "NmBengkel LIKE '%" + txtname.Text + "%'";
}
if (txtaddress.Text.Trim() != "")
{
search = search + " AND Address LIKE '%" + txtaddress.Text + "%'";
}
if (txttelp.Text.Trim() != "")
{
search = search + " AND NoTelp LIKE '%" + txttelp.Text + "%'";
}
if (txtnote.Text.Trim() != "")
{
search = search + " AND Note LIKE '%" + txtnote.Text + "%'";
}
SqlDataSource1.SelectCommand = "SELECT * FROM mst_bengkel where " + search;
}
you can use parameterized Query like
_cmd = new SqlCommand();
_cmd.CommandText = "prc_GetSampleData";
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add("#name", SqlDbType.Varchar).Value = txtname.Text.Trim();
_cmd.Parameters.Add("#address", SqlDbType.Decimal).Value = txtaddress.Text.Trim();
_cmd.Parameters.Add("#telp", SqlDbType.Decimal).Value = txttelp.Text.Trim();
_cmd.Parameters.Add("#note", SqlDbType.Decimal).Value = txtnote.Text.Trim();
_cmd.Connection = _con;
_con.Open();
try
{
sqlDA = new SqlDataAdapter(sqlCmd);
sqlDA.Fill(ds, "SampleData");
}
catch (Exception ex) { _ex = ex; }
finally { if (_con.State == ConnectionState.Open) { _con.Close(); } }
Here is the procedure
Create procedure prc_GetSampleData
#name varchar(50) =null,
#address varchar(50)=null,
#telp varchar(50)=null,
#note varchar(50)=null
AS
BEGIN
Declare #prmname varchar(50)='%%'
Declare #prmaddress varchar(50)='%%'
Declare #prmtelp varchar(50)='%%'
Declare #prmnote varchar(50)='%%'
if #name is not null
begin
set #prmname=#name
end
if #address is not null
begin
set #prmaddress=#address
end
if #telp is not null
begin
set #prmtelp=#telp
end
if #note is not null
begin
set #prmnote=#note
end
SELECT * FROM mst_bengkel where name Like #prmname and address like #prmaddress and telp like #prmtelp and note like #prmnote
END
Use stored procedure.
using System.Data;
using System.Data.SqlClient;
#region Declaration
private SqlConnection _con;
private SqlCommand _cmd;
private SqlDataAdapter _sda;
private Exception _ex;
private SqlDataReader _sdr;
#endregion
protected void btnsearchadvance_Click(object sender, EventArgs e)
{
_con = new SqlConnection(ConfigurationManager.AppSettings["connectionstring"].ToString());
_cmd = new SqlCommand();
_cmd.CommandText = "prc_GetSampleData";
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add("#name", SqlDbType.Varchar).Value = txtname.Text.Trim();
_cmd.Parameters.Add("#address", SqlDbType.Decimal).Value = txtaddress.Text.Trim();
_cmd.Parameters.Add("#telp", SqlDbType.Decimal).Value = txttelp.Text.Trim();
_cmd.Parameters.Add("#note", SqlDbType.Decimal).Value = txtnote.Text.Trim();
_cmd.Connection = _con;
_con.Open();
try
{
_sda = new SqlDataAdapter(_cmd);
_sda.Fill(ds, "SampleData");
}
catch (Exception ex) { _ex = ex; }
finally { if (_con.State == ConnectionState.Open) { _con.Close(); } }
}

Changing the parameter in sql query of ASP.NET page - with button_click event, sql query in every button click

I have a ASP.NET page which have details in below manner.
Date OfficerID DutyID
25-NOV-13 2 666
26-NOV-13 2 666
27-NOV-13 2 666
28-NOV-13 2 666
29-NOV-13 2 666
30-NOV-13 2 666
01-DEC-13 2 666
02-DEC-13 2 523
The above is being populated in gridview through below code snippet
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate and sysdate+18";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
Now I also have a previous button which should output the same page but with sql query slightly changed
select * from duty_rota where duty_date between sysdate-18 and sysdate;
and with every button click the date parameters should be decreased by 18, i.e with 1st previous button click query will be
sysdate-18 and sysdate
with 2nd click
sysdate-36 and sysdate-18
with 3rd click
sysdate-54 and sysdate-36
and so on...
Please help me how could I acheieve it , I was trying to implement it with a variable associated with Previous buttons button click event which would change with every subsequent click. But I am not really able to accomplish it. Can anybody please guide me on this.
Write below code to handle dynamic query on previous and next button click event :
protected void PrevioseButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(false);
this.BindGrid(sqlQuery);
}
protected void NextButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(true);
this.BindGrid(sqlQuery);
}
private string GenerateQuery(bool isNext)
{
if (ViewState["fromDate"] == null && ViewState["toDate"] == null)
{
ViewState["fromDate"] = isNext ? "sysdate+18" : "sysdate-18";
ViewState["toDate"] = isNext ? "sysdate+36" : "sysdate";
}
else
{
var from = ViewState["fromDate"].ToString().Replace("sysdate", string.Empty);
var to = ViewState["toDate"].ToString().Replace("sysdate", string.Empty);
int fromDay = 0;
int toDay = 0;
if (from != string.Empty)
{
fromDay = Convert.ToInt32(from);
}
if (to != string.Empty)
{
toDay = Convert.ToInt32(to);
}
if (!isNext)
{
fromDay = fromDay - 18;
toDay = toDay - 18;
}
else
{
fromDay = fromDay + 18;
toDay = toDay + 18;
}
from = "sysdate";
to = "sysdate";
if (fromDay > 0)
{
from += "+" + fromDay;
}
else if (fromDay < 0)
{
from += fromDay.ToString();
}
if (toDay > 0)
{
to += "+" + toDay;
}
else if (toDay < 0)
{
to += toDay.ToString();
}
ViewState["fromDate"] = from;
ViewState["toDate"] = to;
}
var sqlQuery = "select * from duty_rota where duty_date between " + ViewState["fromDate"] + " and "
+ ViewState["toDate"];
return sqlQuery;
}
private void BindGrid(string sqlQuery)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
On the button click event, try this:
DataTable table = new DataTable();
string connectionString = GetConnectionString();
if (Session["sysdate"] == null || string.IsNullOrEmpty(Session["sysdate"].ToString()))
Session["sysdate"] = "-18";
else
Session["sysdate"] = "+ " + (Convert.ToInt32(Session["sysdate"]) - 18).ToString();
string sysdate = Session["sysdate"].ToString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate " + sysdate + " and sysdate+18 " + sysdate;
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
Me thoughts an ObjectDataSource control would perfectly provide you with a solution...however then I realized that your pagesize varies!
In such a case you need to have your pagination to be disassociated with the gridview. Meaning pagination should be separate and your data which needs to be displayed in the grid view need to be separate. They may have something like a master-child relationship. It means you'd need separate db calls for fetching "each".
You pagination part could be rendered by a gridview or a data list view.
However, if the pagesize on the gridview is always constant you need read this: http://www.codeproject.com/Articles/13963/Implement-Paging-using-ObjectDataSource-with-GridV

How to update sql database table info with excel file using file uploaded

I am trying to update the files in the table that I have created. I am using file uploader to insert my Excel file and upload it to the database. But currently my code creates a new database table each time a file is uploaded, which I don't want it to do. I want to just update/replace the whole file in database table. How do I do this?
This is my code:
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["nConnectionString2"].ConnectionString;
}
private void CreateDatabaseTable(DataTable dt, string tableName)
{
string sqlQuery = string.Empty;
string sqlDBType = string.Empty;
string dataType = string.Empty;
int maxLength = 0;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < dt.Columns.Count; i++)
{
dataType = dt.Columns[i].DataType.ToString();
if (dataType == "System.Int32")
{
sqlDBType = "INT";
}
else if (dataType == "System.String")
{
sqlDBType = "NVARCHAR";
maxLength = dt.Columns[i].MaxLength;
}
if (maxLength > 0)
{
sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
}
else
{
sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType));
}
}
sqlQuery = sb.ToString();
sqlQuery = sqlQuery.Trim().TrimEnd(',');
sqlQuery = sqlQuery + " )";
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
sqlQuery = sb.ToString();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{
string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadExcelFile") + "\\" + fileInfo.Name;
//Save the CSV file in the Server inside 'MyCSVFolder'
FileUpload1.SaveAs(csvFilePath);
//Fetch the location of CSV file
string filePath = Server.MapPath("UploadExcelFile") + "\\";
string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";
// load the data from CSV to DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
if (dtCSV.Rows.Count > 0)
{
CreateDatabaseTable(dtCSV, fileName);
Label1.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
else
{
Label1.Text = "File is empty.";
}
}
else
{
Label1.Text = "Unable to recognize file.";
}
}
}
The code that creates the tables should give an error when you run it if the tables already exists as you never drop them.
That said, one solution might be to add a check to see if the table already exists in the code that creates a new table; it should be something like:
IF OBJECT_ID('TABLE', 'U') IS NULLwhere TABLEit the name of the table that you want to add, so the code might look like:
sb.AppendFormat(string.Format("IF OBJECT_ID({0}, 'U') IS NULL CREATE TABLE {0} (", tableName));
Another, possibly better, option would be to run a query to check if the table exists before you run the CreateDatabaseTable(dtCSV, fileName);statement. You can do the check by executing something like IF OBJECT_ID('tableName', 'U') IS NULL SELECT 1 ELSE SELECT 0 (this would return 1 if the table doesn't exist), and then conditionally execute the CreateDatabaseTablestatement.

CollectionPager Problem With UpdatePanel [duplicate]

I have a problem with the collectionpager and repeater. When I load the page, collectionpager is working fine.. But when I click the search button and bind new data, clicking the page 2 link, it is firing the page_load event handler and bring all the data back again... Notice: All controls are in an UpdatePanel.
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
kayit_getir("SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id ORDER BY Tbl_Icerikler.ID DESC,Tbl_Icerikler.sira ASC");
}}
public void kayit_getir(string SQL){
SqlConnection baglanti = new SqlConnection(f.baglan());
baglanti.Open();
SqlCommand komut = new SqlCommand(SQL, baglanti);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
CollectionPager1.DataSource = dt.DefaultView;
CollectionPager1.BindToControl = Liste;
Liste.DataSource = CollectionPager1.DataSourcePaged;
}
else
{
kayit_yok.Text = "<br /><span class='message information'>Kayıt bulunamadı.</span>";
}
da.Dispose();
baglanti.Close();
CollectionPager1.DataBind();
Liste.DataBind();}
protected void search_Click(object sender, EventArgs e){
string adi = f.temizle(baslik.Text);
string durum = Durum.SelectedValue;
string kayit_bas_t = kayit_bas_tarih.Text;
string kayit_bit_t = kayit_bit_tarih.Text;
string kategori = kategori_adi.SelectedValue;
string SQL = "SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id and";
if (adi != "")
{
SQL = SQL + " Tbl_Icerikler.baslik LIKE '%" + adi + "%' and";
}
if (kategori != "")
{
SQL = SQL + " Tbl_Icerikler.kategori_id=" + kategori + " and";
}
if (durum != "")
{
SQL = SQL + " Tbl_Icerikler.durum='" + durum + "' and";
}
if (kayit_bas_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi>'" + kayit_bas_t + "') and";
}
if (kayit_bit_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi<'" + kayit_bit_t + "') and";
}
SQL = SQL.Remove(SQL.Length - 3, 3);
SQL = SQL + " ORDER BY sira ASC,ID DESC";
try
{
kayit_getir(SQL);
}
catch { }
Recursive(0, 0);}
the code is very bad and you should completely review all of it.
the issue is every time the page load is executed it initializes again you query to the default one (the one with not filter) you should find a way to store somewhere the last query has been execute when you order/filtering your data.
Anyway the are lot of example on the web showing what you are trying to achieve
the below is just one of them
http://www.codeproject.com/KB/webforms/ExtendedRepeater.aspx
try this EnableViewState="false"
You have to bind the CollectionPager again on your search.

CollectionPager Problem With UpdatePanel

I have a problem with the collectionpager and repeater. When I load the page, collectionpager is working fine.. But when I click the search button and bind new data, clicking the page 2 link, it is firing the page_load event handler and bring all the data back again... Notice: All controls are in an UpdatePanel.
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
kayit_getir("SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id ORDER BY Tbl_Icerikler.ID DESC,Tbl_Icerikler.sira ASC");
}}
public void kayit_getir(string SQL){
SqlConnection baglanti = new SqlConnection(f.baglan());
baglanti.Open();
SqlCommand komut = new SqlCommand(SQL, baglanti);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
CollectionPager1.DataSource = dt.DefaultView;
CollectionPager1.BindToControl = Liste;
Liste.DataSource = CollectionPager1.DataSourcePaged;
}
else
{
kayit_yok.Text = "<br /><span class='message information'>Kayıt bulunamadı.</span>";
}
da.Dispose();
baglanti.Close();
CollectionPager1.DataBind();
Liste.DataBind();}
protected void search_Click(object sender, EventArgs e){
string adi = f.temizle(baslik.Text);
string durum = Durum.SelectedValue;
string kayit_bas_t = kayit_bas_tarih.Text;
string kayit_bit_t = kayit_bit_tarih.Text;
string kategori = kategori_adi.SelectedValue;
string SQL = "SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id and";
if (adi != "")
{
SQL = SQL + " Tbl_Icerikler.baslik LIKE '%" + adi + "%' and";
}
if (kategori != "")
{
SQL = SQL + " Tbl_Icerikler.kategori_id=" + kategori + " and";
}
if (durum != "")
{
SQL = SQL + " Tbl_Icerikler.durum='" + durum + "' and";
}
if (kayit_bas_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi>'" + kayit_bas_t + "') and";
}
if (kayit_bit_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi<'" + kayit_bit_t + "') and";
}
SQL = SQL.Remove(SQL.Length - 3, 3);
SQL = SQL + " ORDER BY sira ASC,ID DESC";
try
{
kayit_getir(SQL);
}
catch { }
Recursive(0, 0);}
the code is very bad and you should completely review all of it.
the issue is every time the page load is executed it initializes again you query to the default one (the one with not filter) you should find a way to store somewhere the last query has been execute when you order/filtering your data.
Anyway the are lot of example on the web showing what you are trying to achieve
the below is just one of them
http://www.codeproject.com/KB/webforms/ExtendedRepeater.aspx
try this EnableViewState="false"
You have to bind the CollectionPager again on your search.

Resources