I'm creating Admin Panel using Ajax tab container which has 5 tapPanels and in that each tapPanel, I have one Panel from standard tool. And in that each Panel, I have GridView to show added data. And finally, I have one Add button outside of the Ajax tabContainer. I'll post the design if it allows. The problem is, I don't know the coding for tabContainer. I've created 10 methods so I can call it when Add button clicks.
Here is my code which is not working.
namespace Admin_Panel
{
public partial class add : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["Page"] = "ADD";
}
protected void btnAddCat_Click(object sender, EventArgs e)
{
AjaxControlToolkit.TabContainer container = (AjaxControlToolkit.TabContainer)TabConAddInfo;
AjaxControlToolkit.TabPanel tcTabPanel = new AjaxControlToolkit.TabPanel();
if (tcTabPanel.HeaderText == "Splash")
{
addSplash();
lblMsgAdd.Text = "Added successfully";
}
else if (tcTabPanel.HeaderText == "Main Category")
{
addMainCat();
lblMsgAdd.Text = "Added successfully";
}
else if (tcTabPanel.HeaderText == "Sub Category")
{
addSubCat();
lblMsgAdd.Text = "Added successfully";
}
else if (tcTabPanel.HeaderText == "Business Contact")
{
addBusinessContact();
lblMsgAdd.Text = "Added successfully";
}
else if (tcTabPanel.HeaderText == "Person Contact")
{
addPersonContact();
lblMsgAdd.Text = "Added successfully";
}
}
Int32 fileLength = 0;
string connStr = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
private void addSplash()
{
HttpPostedFile uploadFile = FileLogo.PostedFile;
fileLength = uploadFile.ContentLength;
if (fileLength == 0)
{
string filePath = Server.MapPath(#"\style\img\no-photo-icon.jpg");
string fileName = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
fileLength = (Int32)fs.Length;
Byte[] fileByteArr = new Byte[fileLength];
fs.Read(fileByteArr, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArr);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
else
{
Byte[] fileByteArray = new Byte[fileLength];
Stream streamObject = uploadFile.InputStream;
streamObject.Read(fileByteArray, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArray);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}
private void showSplash()
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("select * from SPLASH", conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(rdr);
GridViewAddSplash.DataSource = dt;
GridViewAddSplash.DataBind();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
private void addMainCat()
{
}
private void showMainCat()
{
}
private void addSubCat()
{
}
private void showSubCat()
{
}
private void addBusinessContact()
{
}
private void showBusinessContact()
{
}
private void addPersonContact()
{
}
private void showPersonContact()
{
}
}
}
My other related question, How to create ActiveTabChanged for Ajax tabContainer
Active_TabChanged
int CurrentTab = TabConAddInfo.ActiveTabIndex;
switch (CurrentTab)
{
case 0:
addSplash();
lblMsgAdd.Text = "Added successfully";
break;
}
etc. You would include that in your btn click event. Obviously I don't know if your TabIndex of zero is the right one to call addSplash() - just call the correct function for each tab.
As for the change of tab - are you talking about raising a javascript function?
OnClientActiveTabChanged="yourfunction";
Related
I want to update invoice and invoice has multiple items i retrieve invoice items from Database to DataGridView now user can remove the items and can add the items and user will click on update button to update the invoice in database.
My Code:
try
{
using (SQLiteConnection con = new SQLiteConnection(AppSettings.ConnectionString()))
{
con.Open();
for (int j = 0; j < dgv.Rows.Count; j++)
{
using (SQLiteCommand sc = new SQLiteCommand("Update Orders Set [Order_No] = #Order_No,[Order_Type] = #Order_Type,[Order_Date] = #Order_Date,[Customer_Name] = #Customer_Name,[Contact] = #Contact,[Adress] = #Adress,[Delivery_Address] = #Delivery_Address,[Rider] = #Rider,[Items] = #Items,[Price] = #Price,[Qty] = #Qty,[Item_Total] = #Item_Total,[Item_Cat] = #Item_Cat,[SubTotal] = #SubTotal,[Discount] = #Discount,[Total_Amount] = #Total_Amount,[Paid_Amount] = #Paid_Amount,[Change_Due] = #Change_Due,[Delivery_Charges] = #Delivery_Charges Where Order_No = '" + Order_No.Text + "' ", con))
{
sc.Parameters.AddWithValue("#Order_No", Order_No.Text);
sc.Parameters.AddWithValue("#Order_Type", Order_Type.Text);
sc.Parameters.AddWithValue("#Order_Date", Order_Date.Text);
sc.Parameters.AddWithValue("#Customer_Name", Customer_Name.Text);
sc.Parameters.AddWithValue("#Contact", Contact.Text);
sc.Parameters.AddWithValue("#Adress", Address.Text);
sc.Parameters.AddWithValue("#Delivery_Address", Delivery_Address.Text);
sc.Parameters.AddWithValue("#Rider", "");
sc.Parameters.AddWithValue("#Items", dgv.Rows[j].Cells[1].Value);
sc.Parameters.AddWithValue("#Price", dgv.Rows[j].Cells[2].Value);
sc.Parameters.AddWithValue("#Qty", dgv.Rows[j].Cells[3].Value);
sc.Parameters.AddWithValue("#Item_Total", dgv.Rows[j].Cells[4].Value);
sc.Parameters.AddWithValue("#Item_Cat", dgv.Rows[j].Cells[5].Value);
sc.Parameters.AddWithValue("#SubTotal", SubTotal.Text);
sc.Parameters.AddWithValue("#Discount", Discount.Text);
sc.Parameters.AddWithValue("#Total_Amount", Total_Amount.Text);
sc.Parameters.AddWithValue("#Paid_Amount", Paid_Amount.Text);
sc.Parameters.AddWithValue("#Change_Due", Change_Due.Text);
sc.Parameters.AddWithValue("#Delivery_Charges", Del_Charges.Text);
sc.ExecuteNonQuery();
}
}
SuccessBox sb = new SuccessBox();
sb.lbl_Change.Text = Change_Due.Text;
sb.label1.Text = "Successfully Updated";
sb.ShowDialog();
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if i add new item and click on update button so this query replaces my all old items with new one.
Suppose i add Samsung S8 so it willl replace my old items to Samsung S8.
And the result is:
Samsung S8 1 $750
Samsung S8 1 $750
Samsung S8 1 $750
Samsung S8 1 $750
Is there any way to do this?
You have to Set The OrderID Parameter in order to Update the desired Item
This will do the Insert, Update, and Delete for you, all via a DataGrid object.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertUpdateDeleteDemo
{
public partial class frmMain : Form
{
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int ID = 0;
public frmMain()
{
InitializeComponent();
DisplayData();
}
//Insert Data
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("insert into tbl_Record(Name,State) values(#name,#state)", con);
con.Open();
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Provide Details!");
}
}
//Display Data in DataGridView
private void DisplayData()
{
con.Open();
DataTable dt=new DataTable();
adapt=new SqlDataAdapter("select * from tbl_Record",con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
txt_Name.Text = "";
txt_State.Text = "";
ID = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
//Update Record
private void btn_Update_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("update tbl_Record set Name=#name,State=#state where ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
//Delete Record
private void btn_Delete_Click(object sender, EventArgs e)
{
if(ID!=0)
{
cmd = new SqlCommand("delete tbl_Record where ID=#id",con);
con.Open();
cmd.Parameters.AddWithValue("#id",ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Delete");
}
}
}
}
I'm trying to make this catalog app that display images with its "title" and "category" but I can't seem to display the image because of an error
on the line that says
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
This is the whole of my code. I need the solution so i can print the image with its corresponding details in a list view. Thank you.
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Books");
comboBox1.Items.Add("Games");
comboBox1.Items.Add("Music");
}
SqlConnection connection = new SqlConnection("Data Source=DESKTOP-4T5BLQ6\\SQLEXPRESS;Initial Catalog=CatalogDB;Integrated Security=True");
SqlCommand command = new SqlCommand();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlDataReader dataReader;
DataTable dataTable = new DataTable();
MemoryStream stream1;
byte[] photo_array;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
int i = 0;
MemoryStream stream = new MemoryStream();
command.CommandText = "insert into EntryTable(Title,Category,Image) values('" + textBox1.Text + "','" + comboBox1.Text + "','" + pictureBox1.Image + "')";
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
if (i > 0)
{
MessageBox.Show("Saved new item in index" + i);
}
connection.Close();
MessageBox.Show("Made New Entry");
showData();
clear();
}
void clear()
{
textBox1.Clear();
pictureBox1.Image = null;
comboBox1.SelectedIndex = -1;
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Images only. |*.jpg; *jpeg; *.png; *.gif; *.bmp;";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
private void showData()
{
connection.Open();
listView1.Clear();
ImageList images = new ImageList();
images.ColorDepth = ColorDepth.Depth32Bit;
listView1.LargeImageList = images;
listView1.LargeImageList.ImageSize = new System.Drawing.Size(100 , 100);
command.Connection = connection;
command.CommandText = "SELECT * FROM EntryTable";
dataAdapter.SelectCommand = command;
dataTable.Clear();
dataAdapter.Fill(dataTable);
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
connection.Close();
}
}
}
Xoriel,
You need to be more specific about what you are asking on SO. Your original post only indicates that you have and error and that it is holding up your app development (welcome to coding). You don't even tell us what error you are getting.
Now you ask how to implement a try catch? You should do a bit of research on your own. As far as try catch, you can start Here.
Your code indicates a lack of understanding about how windows winforms are instantiated and their sequence of events. To me, this indicates that you will have further problems after this one is fixed, so I will add a try catch to your code. It will write the exception to your console.
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
try
{
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
Your true issue is the format in which you are storing the image to the database and the way in which you are retrieving it.
Regards,
Marc
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 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();
}
}
hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?
I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx