I am working in Visual Studio 2010 and I am trying to upload documents via a webpage to an access database. I am not getting any errors when I run my code, but nothing is writing to the database. Here is my on click code to show what I think it is supposed to do.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExtension = Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".doc" || fileExtension.ToLower() != ".docx" || fileExtension.ToLower() != ".pdf")
{
lblInfo.Text = "Only .doc, .docx, or .pdf files are allowed.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
int fileSize = FileUpload1.PostedFile.ContentLength;
if (fileSize > 2097152)
{
lblInfo.Text = "Maximum file size of 2 MB exceeded.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
OleDbCommand update = new OleDbCommand("Update STAFF SET Resume = #Resume WHERE StaffID=#StaffID", DBConnection);
update.Parameters.Add("#Resume", OleDbType.LongVarBinary).Value = FileUpload1.FileContent;
update.Parameters.Add("#StaffID", OleDbType.Integer).Value = txtStaffID.Text;
lblInfo.Text = "File Uploaded";
lblInfo.ForeColor = System.Drawing.Color.Green;
}
}
}
else
{
lblInfo.Text = "Please select a file to upload";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
}
If you could provide any advice or suggestions that would be great. Thanks. I will show the entirety of the code also, just in case it's an issue with the DB connection.
public partial class Staff : System.Web.UI.Page
{
OleDbConnection DBConnection = new OleDbConnection();
OleDbDataAdapter DataAdapter;
DataTable LocalDataTable = new DataTable();
private void ConnectToDatabase()
{
DBConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\CIS470_TPS_System\CIS470_TPS_System\CIS470_TPS_System\App_Data\TpsSystem_DB.mdb";
DBConnection.Open();
DataAdapter = new OleDbDataAdapter("Select * From STAFF", DBConnection);
DataAdapter.Fill(LocalDataTable);
}
private void Page_Load(object sender, EventArgs e)
{
ConnectToDatabase();
}
protected void AccessDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string requestId = GridView1.SelectedRow.Cells[1].Text;
txtSelectedStaff.Text = requestId; //this control holds the selected value
}
protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
}
As suggested in the comments to the question, we can use the FileUpload control's .FileBytes property to supply the value of the query parameter, as in this (simplified) example:
protected void btnUpload_Click(object sender, EventArgs e)
{
using (var con = new OleDbConnection())
{
con.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\staffDb.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
"UPDATE STAFF SET Resume=? " +
"WHERE StaffID=?";
cmd.Parameters.AddWithValue("?", FileUpload1.FileBytes);
cmd.Parameters.AddWithValue("?", 1);
cmd.ExecuteNonQuery();
}
con.Close();
}
}
Related
This is my first time using C# and SQL. I've managed to get the datagridview to work, be it insert, update or delete. However, all the changes that is reflected in the datagridview is NOT updating in the SQL Table (When I open the database and click "Show Table Data", the Insert, Update and Delete changes are not reflected there.)
Please Help! All the videos I've searched up only shows their datagridview changes being reflected, but doesn't show if their SQL Table is actually updated.
My Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.InteropServices;
namespace CRUDProj
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
displaydata();
button3.Visible = false;
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
chk.HeaderText = "Select";
chk.ValueType = typeof(bool);
chk.Name = "chkbox";
infoDataGridView.Columns.Insert(0, chk);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'cRUDDBDataSet.Info' table. You can move, or remove it, as needed.
this.infoTableAdapter.Fill(this.cRUDDBDataSet.Info);
}
private void infoBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.infoBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.cRUDDBDataSet);
}
private void displaydata()
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[Info]";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
DataTable dt = new DataTable();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
sdr.Fill(dt);
infoDataGridView.DataSource = dt;
sqlconn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "insert into [dbo].[Info] values (#Id, #FullName, #NRIC, #Phone, #Temperature, #LocationLevel, #Date)";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id", iDTextBox.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
MessageBox.Show("Record Successfully Inserted");
displaydata();
sqlconn.Close();
}
public string message = string.Empty;
private void button2_Click(object sender, EventArgs e)
{
foreach(DataGridViewRow row in infoDataGridView.Rows)
{
bool issellected = Convert.ToBoolean(row.Cells["chkbox"].Value);
if (issellected)
{
message = Environment.NewLine;
message = row.Cells[1].Value.ToString();
}
}
label1.Text = message;
label1.Visible = true;
button3.Visible = true;
button1.Enabled = false;
button2.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
}
private void button3_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "update [dbo].[Info] set Id=#Id, FullName=#FullName, NRIC=#NRIC, Phone=#Phone, Temperature=#Temperature, LocationLevel=#LocationLevel, Date=#Date where Id=#Id";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id" ,label1.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
infoTableAdapter.Update(cRUDDBDataSet.Info);
sqlconn.Close();
MessageBox.Show("Record Updated Successfully! ");
displaydata();
button3.Visible = false;
button1.Enabled = true;
button2.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
DataRowView drv = infoDataGridView.CurrentRow.DataBoundItem as DataRowView;
DataRow[] rowsToUpdate = new DataRow[] { drv.Row };
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM dbo.Info", sqlconn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(rowsToUpdate);
this.infoTableAdapter.Update(this.cRUDDBDataSet.Info);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
List<String> empselect = new List<String>();
DataGridViewRow row = new DataGridViewRow();
for (int i = 0; i<= infoDataGridView.Rows.Count-1; i++)
{
row = infoDataGridView.Rows[i];
if (Convert.ToBoolean(row.Cells [0].Value)==true)
{
string id = row.Cells[1].Value.ToString();
empselect.Add(id);
}
sqlconn.Open();
foreach (string s in empselect)
{
SqlCommand sqlcomm = new SqlCommand("delete from [dbo].[Info] where Id = ' " + s + " ' ", sqlconn);
sqlcomm.ExecuteNonQuery();
}
sqlconn.Close();
}
MessageBox.Show("Record Deleted Successfully! ");
displaydata();
}
private void iDTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
iDTextBox.Clear();
fullNameTextBox.Clear();
nRICTextBox.Clear();
phoneTextBox.Clear();
temperatureTextBox.Clear();
locationLevelTextBox.Clear();
dateTextBox.Clear();
}
}
}
Bind your DGV to Database this will help you to perform crud operations easily.
This is a sample code on DGV to perform some actions may it will help you. but make sure that you bind your DGV to the database table.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
string _name = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string _lname = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
string _sex = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
string _age = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
if (e.ColumnIndex == dataGridView1.Columns["delete"].Index && e.RowIndex >= 0)
{
if(groupBox1.Visible==true)
{
groupBox1.Visible = false;
}
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
DialogResult result = MessageBox.Show("Do You Want to delete?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (result.Equals(DialogResult.OK) && service.deleterecord(_id, _name, _lname, _age, _sex))
{
MessageBox.Show("deleted record");
this.Close();
}
else
{
MessageBox.Show("not deleted");
}
}
if (e.ColumnIndex == dataGridView1.Columns["edit"].Index && e.RowIndex >= 0)
{
groupBox1.Visible = true;
firstname.Text = _name;
lastname.Text = _lname;
gender.Text = _sex;
age.Text = _age;
}
}
private void update_Click(object sender, EventArgs e)
{
string _fname = firstname.Text;
string _lname = lastname.Text;
string _age = age.Text;
string _sex = gender.Text;
try
{
if (string.IsNullOrWhiteSpace(_fname) || string.IsNullOrWhiteSpace(_lname) || string.IsNullOrWhiteSpace(_age) || string.IsNullOrWhiteSpace(_sex) || gender.Equals(null))
{
MessageBox.Show("Please enter the empty fields");
}
else
{
if (Updatedata("Update Query"))
{
MessageBox.Show("Record Updated");
//this.recordTableAdapter.Fill(this.task2DataSet.record);
groupBox1.Visible = false;
this.Size = new Size(595, 258);
this.Close();
}
else
{
MessageBox.Show("Failed to update");
}
}
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
}
}
I have to create a page an aspx page that allows me to modify the data of the listview row that are associated to a db, but I can't get the values.
I tried to do a query string
protected void EditButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(((Button)sender).Attributes["ID_Persona"]);
Response.Redirect("http://localhost:60082/pages/Edit.aspx" + "?
ID_Persona=" + id);
}
and to take the value on the page where I need it
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = Request.QueryString.Get("ID_Persona").ToString();
}
but I don't know how to display the line I want to edit in the textboxes.
this is the button that redirects to the edit page
protected void EditButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(((Button)sender).Attributes["ID_Persona"]);
Response.Redirect("http://localhost:60082/pages/Edit.aspx" + "?
ID_Persona=" + id);
}
this is the edit page
public partial class Edit : System.Web.UI.Page
{
string constr =
ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = Request.QueryString.Get("ID_Persona").ToString();
}
protected void CustomerUpdate(object sender, EventArgs e)
{
CustomerUpdate();
}
private int Id
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["ID"]) ? int.Parse(Request.QueryString["ID"]) : 0;
}
}
private void CustomerUpdate()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Persona SET Nome=#Nome, Cognome=#Cognome,Email=#Email,CodiceFiscale=#CodiceFiscale WHERE ID=#ID", con))
{
cmd.Parameters.AddWithValue("Nome", TextBox1.Text);
cmd.Parameters.AddWithValue("Cognome", TextBox15.Text);
cmd.Parameters.AddWithValue("Email", TextBox20.Text);
cmd.Parameters.AddWithValue("CodiceFiscale",TextBox22.Text);
cmd.Parameters.AddWithValue("ID", "");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri, false);
Response.Redirect("Dash.aspx");
}
}
}
}
I think that you shuld make public the methods which sends the information like the query but i'm not sure that will work.
I solved that
if (queryy == "1")
{
B2.Visible = false;
var connectionString =
ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM
Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#ID",
Request.QueryString.Get("ID_Persona"));
con.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
TextBox1.Text = rdr["Nome"].ToString();
TextBox15.Text = rdr["Cognome"].ToString();
TextBox20.Text = rdr["Email"].ToString();
TextBox22.Text = rdr["CodiceFiscale"].ToString();
}
}
}
}
How to show progressbar while sending email using backgroundworker in C#. It should show step by step as we can see while we copy anything to our drive.I am reading excel file to send email.
progressbar1.performstep();
OnClick of Button i am showing Progressbar
private void button2_Click(object sender, EventArgs e)
{
progressBar1.Visible = true;
percentageLabel.Visible = true;
backgroundWorker1.RunWorkerAsync();
}
On progress changed event : what to do ??
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progresBar1.PerformStep();
}
On Do work sendmail : (Note : I need backgroundWorker1.ReportProgress should perform step by step, problem is here i knoww but how to do and what to ? please help here)
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(98);
while (!quit)
{
// Code to send email here
sendmail();
}
}
void sendmail()
{
string ConStr = "";
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Program Files\\CreditControl\\CC\\outstanding.xlsx;Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
string query = "SELECT [Agent ID] FROM [Sheet1$] group by [Agent ID] ";
OleDbConnection conn = new OleDbConnection(ConStr);
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
conn.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["Agent ID"].ToString() != "")
{
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Program Files\\CreditControl\\CC\\agent_mail_master.xlsx;Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
string query2 = "SELECT Mail1,Mail2,Mail3,Mail4,Mail5 FROM [Sheet1$] where [Agent ID] = '" + dt.Rows[i]["Agent ID"].ToString() + "'";
OleDbConnection conn2 = new OleDbConnection(ConStr);
if (conn2.State == ConnectionState.Closed)
{
conn2.Open();
}
OleDbCommand cmd1 = new OleDbCommand(query2, conn2);
OleDbDataAdapter sda = new OleDbDataAdapter(cmd1);
System.Data.DataTable dts = new System.Data.DataTable();
sda.Fill(dts);
conn2.Close();
if (dts.Rows.Count > 0)
{
try
{
SmtpClient SmtpServer = new SmtpClient();
MailMessage mail = new MailMessage();
SmtpServer.Credentials = new System.Net.NetworkCredential("");
SmtpServer.Port = 25;
SmtpServer.Host = "";
mail.From = new MailAddress("");
if (dts.Rows[0]["Mail1"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail1"].ToString());
if (dts.Rows[0]["Mail2"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail2"].ToString());
if (dts.Rows[0]["Mail3"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail3"].ToString());
if (dts.Rows[0]["Mail4"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail4"].ToString());
if (dts.Rows[0]["Mail5"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail5"].ToString());
mail.Subject = "";
mail.IsBodyHtml = true;
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Program Files\\CreditControl\\CC\\outstanding.xlsx;Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
string query3 = "Select [Date],[Agency Name] ,[Agent ID],[Delay Days],[OD Amount],[Receipt Amount],[Outstanding Amount],Remarks,[Entered By] FROM [Sheet1$] where [Agent ID] ='" + dt.Rows[i]["Agent ID"].ToString() + "'";
OleDbConnection conn3 = new OleDbConnection(ConStr);
OleDbCommand cmd2 = new OleDbCommand(query3, conn3);
OleDbDataAdapter oda = new OleDbDataAdapter(cmd2);
System.Data.DataTable dta = new System.Data.DataTable();
oda.Fill(dta);
conn3.Close();
StringBuilder sb = new StringBuilder();
mail.Body = sb.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
quit = true;
}
ON backgroundWorker_RunWorkerCompleted success message :
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
progressBar1.Visible = false;
percentageLabel.Text = "";
MessageBox.Show("Error");
return;
}
else
{
MessageBox.Show("Processed successfully");
System.Windows.Forms.Application.Exit();
}
}
you need to fire the ProgressChangedEvent. something like
bgWorker.ReportProgress( PercentageCompleted(...) );
also be advised that progressBar1.Value expects an Int32 between 0 .. 100 and not a Double between 0 .. 1 (from your code it is not obvious what value you are reporting to your BackgroundWorker)
for ReportStep be sure you set all the required properties. you can find an example on MSDN here
http://msdn.microsoft.com/en-us/library/system.windows.forms.progressbar.performstep(v=vs.110).aspx
so in that case you would need to call pbar1.ReportStep() in your ProressChanged-Method instead of setting the Value of pbar1 directly.
EDIT: this is a very basic example from a derived BackgroundWorker how to deal with these events
public sealed class MyBackgroundWorker : BackgroundWorker
{
public MyBackgroundWorker(ProgressBar pBar)
{
this.MyProgressBar = pBar;
this.WorkerReportsProgress = true;
this.WorkerSupportsCancellation = false;
this.DoWork += MyBackgroundWorker_DoWork;
this.ProgressChanged += MyBackgroundWorker_ProgressChanged;
this.RunWorkerCompleted += MyBackgroundWorker_RunWorkerCompleted;
}
public ProgressBar MyProgressBar { get; private set; }
void MyBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Finish");
}
void MyBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
SendMail();
}
void MyBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Boolean either = true; // These are your choices
if (either)
{
// If the ProgressBar has been properly configured regarding
//
// this.myProgressBar.Minimum
// and
// this.myProgressBar.Maximum
//
// you can simply call
this.MyProgressBar.PerformStep();
}
else
{
// If the Progressbar has not been properly configured,
// you have to assign the value provided by
// ProgressChangedEvents e like this
this.MyProgressBar.Value = e.ProgressPercentage;
}
}
private Boolean SendMail()
{
// foreach mail in MailsToSend ...
// Snip - I assume your code for sending mails works correctly
try
{
// Snip
}
catch (Exception ex)
{
// Snip
}
finally
{
this.ReportProgress( (100 * cntMailsSent) / cntTotalMailsToSend);
}
// quit = true; // What do you use this for?
}
}
I have a catalog function whereby user can filter their selection by clicking radiobutton. For example, by selecting the Dining radiobutton, all packages related to dining would appear.
And i using DataList1.Items.Count method to count the number search result. I had implement this method in the page_load, however the value of the number of datalist keep displaying previously loaded datalist.
Here is my code :
protected void Page_Load(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString1"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT CategoryID, CatName from Category";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
//DataList1.DataSource = reader;
DataList1.DataBind();
// CommandBehavior.CloseConnection will automatically close connection
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource1";
if (RadioButtonList1.SelectedIndex == 0)
{
Session["catID"] = 1;
}
else if (RadioButtonList1.SelectedIndex == 1)
{
Session["catID"] = 2;
}
else if (RadioButtonList1.SelectedIndex == 2)
{
Session["catID"] = 3;
}
else if (RadioButtonList1.SelectedIndex == 3)
{
Session["catID"] = 4;
}
else if (RadioButtonList1.SelectedIndex == 4)
{
Session["catID"] = 5;
}
else
{
Session["catID"] = 8;
}
}
I had tried to place the Item.Count in other places of this code, but same problem persist..
Try this,
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
}
Here i have write the coding for image upload control.but getting some RUNTIME error.error sows in SqlConnection place
first i have
1.Image name box - Textbox
2.Image Upload control - asp imageupload control
3.Upload button
ERROR :Object synchronization method was called from an unsynchronized block of code.
Code Below
public partial class ProfileDetails : System.Web.UI.Page
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
//SqlConnection con = new SqlConnection("Data Source=CHATHU-LAPTOP;Initial Catalog=ProfilemgtDB;User ID=sa;Password=sa123");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void Upload_Click(object sender, EventArgs e)
{
string path = Server.MapPath("images/");
if (FileUpload1.HasFile)
{
string ext = Path.GetExtension(FileUpload1.FileName);
if (ext == ".jpg" || ext == ".png")
{
FileUpload1.SaveAs(path + FileUpload1.FileName);
string name = "~/images/" + FileUpload1.FileName;
string s = "Insert into Profile values('" + TextBox12.Text.Trim() + " '.'" + name + "' )";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(s, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("File Uploaded");
}
else
{
Response.Write("You can upload only JPG & PNG");
}
}
else {
Response.Write("Please Select File");
}
}
}
ERROR :Object synchronization method was called from an unsynchronized block of code.
Nimesh,
I do not see anything wrong in the code. However, you may want to check if your web.config contains the same connectionStrings name as mentioned in your code (which is ConnectionString).
Also, refer the following links
http://www.ezzylearning.com/tutorial.aspx?tid=4287517
http://forums.asp.net/t/1757347.aspx/1
Hope this helps.