How to display image from database in c#. I am getting below error:-
Parameter Is Not Valid
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
Utilities.ClearControls(gbxMain);
AssociateID = 0;
MainModuleBO objMainModuleBO = new MainModuleBO();
string[] strReturnValue;
DataTable dtSearch = objMainModuleBO.GetSearchData(this.MasterFormId);
DataGridViewColumnPropertiesCollection objDataGridViewColumnPropertiesCollection = new DataGridViewColumnPropertiesCollection();
objDataGridViewColumnPropertiesCollection.Add(MSTAssociateMasterTO.ASSOCIATEID, "Associate Id", MSTAssociateMasterTO.ASSOCIATEID, true, true, 100);
objDataGridViewColumnPropertiesCollection.Add(MSTAssociateMasterTO.ASSOCIATENAME, "Associate Name", MSTAssociateMasterTO.ASSOCIATENAME, true, false, 500);
frmSearch objfrmSearch = new frmSearch();
objfrmSearch.dtSearch = dtSearch;
objfrmSearch.objDataGridViewColumnPropertiesCollection = objDataGridViewColumnPropertiesCollection;
objfrmSearch.ShowDialog();
strReturnValue = objfrmSearch.strReturnValue;
if (strReturnValue.Length > 0)
{
MSTAssociateMasterBO objMSTAssociateMasterBO = new MSTAssociateMasterBO();
DataTable dt = objMSTAssociateMasterBO.SelectDataById(Utilities.TextToInt(strReturnValue[0]));
AssociateID = Utilities.TextToInt(strReturnValue[0]);
Utilities.BindFormData(this, dt);
pictureBox1.Image = null;
foreach (DataRow dr1 in dt.Rows)
{
picbyte = (byte[])dr1["AssociateImageData"];
MemoryStream ms = new MemoryStream(picbyte);
pictureBox1.Image = Bitmap.FromStream(ms); // here is error occure
}
Utilities.EnableDisableControls(gbxMain, false);
Utilities.EnableDisableButtons(this, CustomControls.ButtonEvent.SearchClick);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);// (this.Controls.Find("txtName", true)[0].GetType().ToString());
}
}
Related
This Code will work when code run from visual studio.
But Not work when host on local host. not call to printer.
protected void btnsave_Click(object sender, EventArgs e)
{
try
{
objBel.BillId = lblbillid.Text;
objBel.NetAmount = txtnetbillamt.Text;
objBel.PDiscount = txtdiscountpercentage.Text;
objBel.DiscountA = txtdiscountamount.Text;
objBel.TaxAmt = txttaxamount.Text;
objBel.PaymentMode = ddlpaymentMode.SelectedItem.Text;
if (ddlpaymentMode.SelectedItem.Text == "Cheque")
{
objBel.ChequeNo = txtchno.Text;
if (txtDate.SelectedDate != null)
{
objBel.ChequeDate = txtDate.SelectedDate.Value.ToString("dd-MM-yyyy");
}
objBel.ChequeDetails = txtotherdetails.Text;
}
if (rbyes.Checked)
{
objBel.ThirdParty = txtthirdpartydiscription.Text;
}
objBel.FinalAmt = txtfinalamount.Text;
objBel.UserId = Convert.ToInt32(Session["UserId"]);
objBel.Time = DateTime.Parse(DateTime.Now.ToString()).ToString("hh:mm tt");
int i = objBal.UpdateBill(objBel);
if (i > 0)
{
Session["Billid"] = "";
DataTable dt = new DataTable();
dt = objBal.BillGenrate(lblbillid.Text);
ReportDocument doc = new ReportDocument();
doc.Load(Server.MapPath("~/CrystalReport/BillPrint.rpt"));
doc.SetDataSource(dt);
if (File.Exists(HttpContext.Current.Server.MapPath("\\Billprints\\Invoice.txt")))
File.Delete(HttpContext.Current.Server.MapPath("\\Billprints\\Invoice.txt"));
string fileName = Server.MapPath("\\Billprints\\") + "Invoice.txt";
doc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.Text, fileName);
doc.Refresh();
doc.PrintToPrinter(1, false, 0, 0);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Error Occur Try Again !!')", true);
}
}
catch { }
}
I am creating a program that creates, writes, and saves an xml file. When I try to open the saved file I get an error that says the file cannot be accessed because it is being used by another process. I assumed it was because I didn't close the filestream after I saved the file so I made the correction. I still can't open the file and I receive the same error. I'm not sure what the issue is beyond this point. How can I fix this?
namespace XML_DataSets
{
public partial class FormAddNew : Form
{
XmlSerializer xs;
List<Class1> ls;
//create the DataTable
DataTable dt = new DataTable("Contact");
XDocument xd = new XDocument();
public FormAddNew()
{
InitializeComponent();
ls = new List<Class1>();
xs = new XmlSerializer(typeof(List<Class1>));
//create columns for the DataTable
DataColumn dc1 = new DataColumn("Id");
dc1.DataType = System.Type.GetType("System.Int32");
dc1.AutoIncrement = true;
dc1.AutoIncrementSeed = 1;
dc1.AutoIncrementStep = 1;
//add columns to the DataTable
dt.Columns.Add(dc1);
dt.Columns.Add(new DataColumn("Name"));
dt.Columns.Add(new DataColumn("Age"));
dt.Columns.Add(new DataColumn("Gender"));
//create DataSet
DataSet ds = new DataSet();
ds.DataSetName = "AddressBook";
ds.Tables.Add(dt);
}
private void buttonCreate_Click(object sender, EventArgs e)
{
DataRow row = dt.NewRow();
row["Name"] = textBoxName.Text;
row["Age"] = textBoxAge.Text;
row["Gender"] = textBoxGender.Text;
dt.Rows.Add(row);
dataGridView1.DataSource = dt;
//dt.WriteXml("Contacts.xml");
xd = WriteDt2Xml(dt);
}
public static XDocument WriteDt2Xml(DataTable dt)
{
using (var stream = new MemoryStream())
{
dt.WriteXml(stream);
stream.Position = 0;
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader reader = XmlReader.Create(stream, settings);
reader.MoveToContent();
if (reader.IsEmptyElement) { reader.Read(); return null; }
return XDocument.Load(reader);
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream input = null;
OpenFileDialog dialog = new OpenFileDialog();
openFileDialog.Filter = "xml file | *.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((input = openFileDialog.OpenFile()) != null)
{
FileStream fs = new FileStream(#openFileDialog.FileName.ToString(), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
ls = (List<Class1>)xs.Deserialize(fs);
dataGridView1.DataSource = ls;
fs.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR");
}
}
}
}
}
#Daniel Advise taken well...I refactored the code and see the error you referred to. I checked out the two links you provided as examples. I made corrections but I still get the same result.
First change the way you open the file to:
using (var fs = new FileStream(#openFileDialog.FileName, FileMode.Open, FileAccess.Read))
{
ls = (List<Class1>) xs.Deserialize(fs);
dataGridView1.DataSource = ls;
}
an then try to check (Debug) the entire Exception in openToolStripMenuItem_Click event:
System.InvalidOperationException was caught
HResult=-2146233079
Message=There is an error in XML document (2, 2).
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at WindowsFormsApplication1.FormAddNew.openToolStripMenuItem_Click(Object sender, EventArgs e) in c:\Users\admin\Documents\Visual Studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\FormAddNew.cs:line 131
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=<AddressBook xmlns=''> was not expected. --The problem!
Source=Microsoft.GeneratedCode
StackTrace:
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read3_ArrayOfClass1()
InnerException:
Then read:
xmlns='' was not expected when deserializing nested classes
{"<user xmlns=''> was not expected.} Deserializing Twitter XML
Update:
You need an atomic object when desalinizing like:
public class AddressBook
{
public AddressBook()
{
Contacts = new List<Contact>();
}
public List<Contact> Contacts { get; set; }
}
public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
}
and I would suggest to get rid of xDocument, DataSet & DataTable. they add too much complication for nothing. and I guess the reason u r using them because of DataGrid which is minor concern, focus on coding first:
private readonly XmlSerializer xs;
private AddressBook ls;
private int _counter = 0;
public FormAddNew2()
{
InitializeComponent();
ls = new AddressBook();
xs = new XmlSerializer(typeof(AddressBook));
}
private void buttonCreate_Click(object sender, EventArgs e)
{
var addressBookContact2 = new Contact
{
Id = ++_counter,
Name = textBoxName.Text,
Age = textBoxAge.Text,
Gender = textBoxGender.Text
};
ls.Contacts.Add(addressBookContact2);
dataGridView1.DataSource = null; // strangly u need this
dataGridView1.DataSource = ls.Contacts;
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
var saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = #"C:\";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Select save location file name";
saveFileDialog.Filter = "XML-File | *.xml";
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
using(var writer = new StreamWriter(saveFileDialog.FileName))
{
xs.Serialize(writer, ls);
MessageBox.Show(saveFileDialog.FileName);
}
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "xml file | *.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
using (var reader = new StreamReader(#openFileDialog.FileName))
{
ls = (AddressBook) xs.Deserialize(reader);
_counter = 0;
dataGridView1.DataSource = ls.Contacts;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "ERROR");
}
}
}
I tried to write code to import an Excel file to a database using C# and ADO.net I finally got the code to run but the output is wrong.
using Excel;
using System.IO;
namespace ExpPerson
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnImport_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog op = new OpenFileDialog();
op.Filter = "Excel Workbook| *.xls;*.xlsx;*.xlsm";
if (op.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(op.FileName, FileMode.Open);
IExcelDataReader excelreader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelreader.AsDataSet();
MaamoonKhalidIssueEntities db = new MaamoonKhalidIssueEntities();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows)
{
Person addtable = new Person()
{
nname = Convert.ToString(dr[0]),
ncode = Convert.ToString(dr[1]),
nTel1 = Convert.ToString(dr[2]),
nTel2 = Convert.ToString(dr[3]),
nFax = Convert.ToString(dr[4]),
nEmail = Convert.ToString(dr[5]),
nAdd = Convert.ToString(dr[6])
};
}
}
db.SaveChanges();
excelreader.Close();
stream.Close();
MessageBox.Show("Import Sucess","Good",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
But there is an issue where the code runs without any errors but the data in the database isn't right and I can't figure out what is wrong.
You need to call db.People.Add(addtable); on each iteration of the DataRow loop.
So:
foreach (DataRow dr in table.Rows)
{
Person addtable = new Person()
{
nname = Convert.ToString(dr[0]),
ncode = Convert.ToString(dr[1]),
nTel1 = Convert.ToString(dr[2]),
nTel2 = Convert.ToString(dr[3]),
nFax = Convert.ToString(dr[4]),
nEmail = Convert.ToString(dr[5]),
nAdd = Convert.ToString(dr[6])
};
db.People.Add(addtable)
}
Otherwise, Entity Framework doesn't know you want them inserted to the database.
In the page_load I'm creating dynamically the headers using data from SpGetCompanies, which is working fine. Then I'm trying to add a ListView to every dynamically created accordion pane with the data source SpSearchPublicationsTop1.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
SQLConnection dataAccessor = new SQLConnection();
dtCompanies = dataAccessor.SpGetCompanies();
if (dtCompanies.Rows.Count > 0)
{
AccordionPane pn;
Label lblContent;
int j = 0;
for (int i = 0; i < dtCompanies.Rows.Count; i++)
{
lblHeader = new Label();
lblHeader.Text = dtCompanies.Rows[i][1].ToString();
lblContent = new Label();
lblContent.Text = "Hallo";
pn = new AccordionPane();
pn.ID = "Pane" + j;
pn.HeaderContainer.Controls.Add(lblHeader);
ListView view = new ListView();
view.LayoutTemplate = new LayoutTemplate();
view.ItemTemplate = new ItemTemplate();
//view = (ListView)FindControl("lv_result");
view.DataSource = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
view.DataBind();
#region commented stuff
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// //view = (ListView)FindControl("lv_result");
// //column1.Text = dt2.Rows[0][0].ToString();
// //view.Columns.Add(column1);
// //Label lblAcronym = new Label();
// //lblAcronym.Text = dt2.Rows[0][0].ToString();
// //view.DataSource = lblAcronym;
// view.DataSource = dt2;
// view.DataBind();
//}
//listView1.Columns.Add(column1);
//foreach (DataRow dr in dt2.Rows)
//{
// ListViewItem lvi = new ListViewItem(dr[0].ToString()); //1.st column in datatable, instead of 0 you can write column`s name like: ["CustomerID"]
// lvi.SubItems.Add(dr[1].ToString()); //2nd column from datatable
// view.Items.Add(lvi);
//}
//this.Controls.Add(view);
//ListView lv_result = new ListView();
////lv_result.ItemTemplate = new ItemTemplate();
//lv_result.ID = "lvpane" + i;
//lv_result.Visible = true;
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// lv_result.DataSource = dt2;
// lv_result.DataBind();
//}
//var level2 = (ListView)FindControl("lv_result");
//level2.ItemTemplate = view.ItemTemplate;
////level2.DataSource = dt2(e.AccordionItem.DataItemIndex);
////level2.DataBind();
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// level2.DataSource = dt2;
// level2.DataBind();
//}
#endregion
pn.ContentContainer.Controls.Add(view);
//pn.ContentContainer.Controls.Add(lblContent);
Accordion1.Panes.Add(pn);
++j;
}
}
}
}
private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var ol = new HtmlGenericControl("ol");
var li = new HtmlGenericControl("li") { ID = "itemPlaceholder" };
ol.Controls.Add(li);
container.Controls.Add(ol);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var li = new HtmlGenericControl("li");
li.DataBinding += DataBinding;
container.Controls.Add(li);
}
public void DataBinding(object sender, EventArgs e)
{
var container = (HtmlGenericControl)sender;
var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
container.Controls.Add(new Literal() { Text = dataItem.ToString() });
}
}
With the code above the headers from the accordion are working fine, but instead of the ListView data in the content I'm only getting: System.Data.DataRowView
What am I doing wrong?
You are missing a call to:
DataBinder.Eval(container.DataItem, "YouBindingProperty");
Example:
public void DataBinding(object sender, EventArgs e)
{
var genericControl = (HtmlGenericControl)sender;
var container = (ListViewDataItem)container.NamingContainer;
container.Controls.Add(new Literal() { Text = DataBinder.Eval(container.DataItem, "YouBindingProperty") });
}
I am using Radgrid with pager. When clicking on the next page number on a pager the data is not displaying(not binding the data). Can anyone help me to fix this. here is my code.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
Session["SearchRes"] = null;
if (Session["TaskName"] != null)
lblTskName.Text = Session["TaskName"].ToString();
Session["FilColms"] = null;
Session["SortExp"] = null;
Session["FilExp"] = null;
Session["ViewAll"] = null;
BindGrid();
}
}
catch (Exception ex)
{
throw ex;
}
}
private void BindGrid()
{
try
{
DataSet dsResult = new DataSet();
clsSearch_BL clsObj = new clsSearch_BL();
clsObj.TaskID = (string)Session["TaskID"];
clsObj.CustName = (string)Session["CustName"];
clsObj.MarketName = (string)Session["MarketName"];
clsObj.HeadendName = (string)Session["HeadendName"];
clsObj.SiteName = (string)Session["SiteName"];
clsObj.TaskStatus = (string)Session["TaskStatus"];
clsObj.OrdType = (string)Session["OrdType"];
clsObj.OrdStatus = (string)Session["OrdStatus"];
clsObj.ProName = (string)Session["ProName"];
clsObj.LOC = (string)Session["LOC"];
clsObj.QuoteID = (string)Session["QuoteID"];
clsObj.CMNumber = (string)Session["CMNumber"];
if (Session["SearchRes"] == null)
{
dsResult = clsObj.getSearchResults_BL(clsObj);
Session["SearchRes"] = dsResult;
}
else
dsResult = (DataSet)Session["SearchRes"];
DataView dataView = dsResult.Tables[0].DefaultView;
rg200.DataSource = dsResult;
rg200.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
protected void rg200_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
if (Session["TaskID"] != null)
{
string strTaskID = (string)Session["TaskID"];
if (strTaskID != string.Empty)
{
clsTaskUpdates_BL objBL = new clsTaskUpdates_BL();
GridEditableItem editedItem = e.Item as GridEditableItem;
//Get the primary key value using the DataKeyValue.
string OrdID = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["orderId"].ToString();
//Access the textbox from the edit form template and store the values in string variables.
string ClarifyAccountNbr = ((GridTextBoxColumnEditor)editedItem.EditManager.GetColumnEditor("Clarify Account Nbr")).TextBoxControl.Text;
string SiteID = ((GridTextBoxColumnEditor)editedItem.EditManager.GetColumnEditor("Site ID")).TextBoxControl.Text;
string QuoteID = ((GridTextBoxColumnEditor)editedItem.EditManager.GetColumnEditor("Quote ID")).TextBoxControl.Text;
CheckBox chkEDP = ((GridCheckBoxColumnEditor)editedItem.EditManager.GetColumnEditor("EDP Created?")).CheckBoxControl;
//string ClarifyAccountNbr = (editedItem["Clarify Account Nbr"].Controls[0] as TextBox).Text;
//string SiteID = (editedItem["Site ID"].Controls[0] as TextBox).Text;
//string QuoteID = (editedItem["Quote ID"].Controls[0] as TextBox).Text;
//CheckBox chkEDP = (editedItem["EDP Created?"].Controls[0] as CheckBox);
try
{
objBL.setTask200_Bl(OrdID, ClarifyAccountNbr, SiteID, QuoteID, chkEDP.Checked);
Session["SearchRes"] = null;
BindGrid();
}
catch (Exception ex)
{
rg200.Controls.Add(new LiteralControl("Unable to update Employee. Reason: " + ex.Message));
e.Canceled = true;
}
}
}
}
protected void rg200_PageIndexChanged(object source, GridPageChangedEventArgs e)
{
try
{
rg200.CurrentPageIndex = e.NewPageIndex;
BindGrid();
}
catch (Exception ex)
{
throw ex;
}
}
Your code shows that you use binding with DataBind() calls. In this way you should manually change the page index hooking PageIndexChanged, assign data source to the grid and bind it. Alternatively, use NeedDataSource binding to spare some manual coding.