how to reference to a fileupload control in a dataset - c#

In my program, when user wants to edit a record, and presses Edit button, a new window opens up with all the fields and record information is rendered into the respective fields giving user an option to edit any field information they require.
I have added a fileupload control to my webform fields. But I am not sure how to reference fileupload control on my new popped up window .. I am not sure if I am explaining my problem very clearly or not but I will try to explain it with the help of following code:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
lblSet.Text = GridView1.Rows[e.NewEditIndex].Cells[2].Text;
MultiView1.SetActiveView(vRecord);
btnSave.Visible = false;
btnBacktoHome.Visible = true;
//this.lblMedium.Text = GridView1.Rows[e.NewEditIndex].Cells[1].Text;
using (SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS;Initial Catalog=PIMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
String sql = "select [DocumentID],[Ref],[Subject],[Src],[Dst],[Medium],[Date_Printed],[Date_Received],[Document_Type],[Action_Required],[Due_Date],[Actual_Date],[Content],[Tag],[Issue_No],[Attachment],[Notes],[Assigned_To],[Reply_Ref],[Priority],[Status],[Response],[Physical_File_No],[Physical_Rack_Location] from dbo.Documents1 where [DocumentId]=N'" + GridView1.Rows[e.NewEditIndex].Cells[2].Text + "'";
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
//SqlDataAdapter da = new SqlDataAdapter(sql,con);
//DataTable dt = new DataTable();
DataSet ds = new DataSet();
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(ds);
}
this.txtRef.Text = ds.Tables[0].Rows[0][1].ToString();
this.txtSubject.Text = ds.Tables[0].Rows[0][2].ToString();
this.ddlSource.Text = ds.Tables[0].Rows[0][3].ToString();
this.ddlDestination.Text = ds.Tables[0].Rows[0][4].ToString();
this.ddlMedium.Text = ds.Tables[0].Rows[0][5].ToString();
this.txtDatePrinted.Text = ds.Tables[0].Rows[0][6].ToString();
this.txtDateReceived.Text = ds.Tables[0].Rows[0][7].ToString();
this.ddlDocumentType.Text = ds.Tables[0].Rows[0][8].ToString();
this.cbxAction.Checked = ds.Tables[0].Rows[0][9].Equals(cbxAction.Checked);
this.txtDueDate.Text = ds.Tables[0].Rows[0][10].ToString();
this.txtActualDate.Text = ds.Tables[0].Rows[0][11].ToString();
this.txtContent.Text = ds.Tables[0].Rows[0][12].ToString();
this.txtTag.Text = ds.Tables[0].Rows[0][13].ToString();
this.txtIssue.Text = ds.Tables[0].Rows[0][14].ToString();
//this.fileupload1 = ds.Tables[0].Rows[0][15] ;
this.txtNotes.Text = ds.Tables[0].Rows[0][16].ToString();
this.ddlAssignedTo.Text = ds.Tables[0].Rows[0][17].ToString();
this.txtReplyRef.Text = ds.Tables[0].Rows[0][18].ToString();
this.ddlPriority.Text = ds.Tables[0].Rows[0][19].ToString();
this.ddlStatus.Text = ds.Tables[0].Rows[0][20].ToString();
this.ddlResponse.Text = ds.Tables[0].Rows[0][21].ToString();
this.txtPhysicalFileNo.Text = ds.Tables[0].Rows[0][22].ToString();
this.txtPhysicalRackLocation.Text = ds.Tables[0].Rows[0][23].ToString();
if (con != null)
{
con.Close();
}
btnUpdate.Visible = true;
btnSearch.Visible = false;
BindGrid();
}
}
}
Basically when user clicks edit, what my code does is, reads the relevant record in the sql server and loads it from there to a new popped up window in my webform .. puts all the information in the related fields.
I read online that reading varbinary data from sql and binding it into the webform is not as simple as calling text data. (maybe I am wrong, please correct me if i am). I am not really worried about fetching data from sql server into the webform, I am worried about referring to the upload control in the new window because if user add a new file in fileupload control in the popped up window and if its not referenced in my code, my program ignores the new uploaded file which is a big flaw in my code.
Problem is with this line of code:
//this.fileupload1 = ds.Tables[0].Rows[0][15] ;
I have commented it out for other code to run.
I am stuck with it for a whole week. Any help will be so much appreciated. Thanks in advance.

You can't bind a record to a file upload control, this control is for uploading files
not
downloading.
Have a look at this link for how to download files.
The upload control should be used to replace the existing file,when the user chooses to replace it i.e. the user will upload a new file and in your business logic you need to update this record using the existing record ID.
In your case I'd bind the ID of the attachment to a hidden field in the grid and leave the upload control alone. When the record is updated check if the file upload control has a file and then using the value of the attachment update the attachment.
Edit: From here I believe you would need to add something along the lines of:
FileUpload file = ((FileUpload)(GridView1.Rows[e.NewEditIndex].FindControl("myFileUploadControl")));
You need to give your file upload control an ID of myFileUploadControl (or whatever you want)
This question also discusses using a fileupload control in a gridview.

Related

How can I redirect to Report Viewer?

I am facing a problem while working with Reports in WPF... I have created an event
private void Window_Loaded(object sender, RoutedEventArgs e) {
try {
admissionReportViewer.Owner = Window.GetWindow(this);
if (_admissionNumber != 0) {
rd.Load(#"C:\\Users\Sohaib Khalid\source\repos\SMS Degree College\Reports\AdmissionForm - Copy.rpt");
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Other"].ConnectionString;
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("SearchStudentInfoAllById", conn);
sda.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
sda.SelectCommand.Parameters.AddWithValue("#AdmissionNumber", _admissionNumber);
sda.SelectCommand.Parameters.AddWithValue("#Active", _active);
DataSet ds = new DataSet();
sda.Fill(ds, "StudentTable");
rd.SetDataSource(ds);
admissionReportViewer.ViewerCore.ReportSource = rd;
}
}
catch(Exception err) {
this.ShowMessageAsync("No data", err.ToString());
Debug.WriteLine(err.ToString());
}
after this report also load but it again, ask for parameters:
and also credentials of server login
Can Anybody tell me why it is again asking for parameters?
Thanks
I never used ReportViewer in WPF app, but used it a couple of time on ASP.NET
If WPF works in the same way, you're code is wrong:
The report is using the data source you set up for design it and not the one you're passing to it
You're storing the parameter value in the data adapter (query) and not in the report parameters
This is why your report ask for both.
I'll share a bit of code for ASP, try to check if it can be the same for WPF or if you have to change it:
// Local mode says to use the datasource we are giving to the report
// instead of the one we used to design it
reportViewer.ProcessingMode = ProcessingMode.Local;
// Set the path of the report file
LocalReport localReport = reportViewer.LocalReport;
localReport.ReportPath = "PATH_OF_YOUR_REPORT";
// Extract data from the DB (remember to insert the parameters in the query)
var dataset = GetDataSet();
// Assign the dataset to the report source (we need a ReportDataSource)
var source = new ReportDataSource();
source.Name = "SOURCE_NAME_USED_IN_THE_REPORT";
source.Value = dataset.Tables["YOUR_TABLE"];
// Add the source to the report
localReport.DataSources.Add(source);
// Create your report parameter (ex: fromDate)
var paramFromDate = new ReportParameter();
paramDataDa.Name = "fromDate";
paramDataDa.Values.Add(paramFromDate.ToShortDateString());
// Set the report parameters for the report
localReport.SetParameters(new ReportParameter[] { fromDate });
I hope this can help you but remember, it is for ASP and not for WPF.
So try to adapt it to WPF and see if they work in the same way

Saving to database, then reading from database, data is not there

I have this page, where the user can modify it's information. When the page loads, it fills in the users information into the text input fields. You can then change your information and hit save. The data should be saved to the database and that should also be reflected in the text fields, because of the refresh. But it does not save the data. If I remove the reading of the data, the data is saved when the button is clicked, but when the data reading is there, the data is not saved.
This is the code in the "read the data" part, this is in the Page_Load():
string loggedInUser = System.Web.HttpContext.Current.User.Identity.Name;
SqlConnection ConnectDb = new SqlConnection("Data Source=serverHere;Initial Catalog=catalogHere;User ID=userNameHere;Password=passwordHere;"); //Opretter database connection string
SqlDataReader infoReader = null;
SqlCommand getUserInfo = new SqlCommand("SELECT firstName,lastName,age,city,contact,bio FROM UserInfo WHERE userName = #userName", ConnectDb);
getUserInfo.Parameters.Add("#userName", loggedInUser);
ConnectDb.Open();
infoReader = getUserInfo.ExecuteReader();
infoReader.Read();
{
tbInfoFirstName.Text = infoReader["firstName"].ToString();
tbInfoLastname.Text = infoReader["lastName"].ToString();
tbInfoAge.Text = infoReader["age"].ToString();
tbInfoCity.Text = infoReader["city"].ToString();
tbInfoKontakt.Text = infoReader["contact"].ToString();
tbInfoAbout.Text = infoReader["bio"].ToString();
};
ConnectDb.Close();
This is the code for the save button:
string loggedInUser = System.Web.HttpContext.Current.User.Identity.Name;
SqlConnection ConnectDb = new SqlConnection("Data Source=serverHere;Initial Catalog=catalogHere;User ID=userNameHere;Password=passwordHere;");
SqlCommand SavePersonInfo = new SqlCommand("UPDATE UserInfo SET firstName = #firstName,lastName = #lastName,age = #age,city = #city,contact = #contact,bio = #bio WHERE userName = #userName", ConnectDb);
SavePersonInfo.Parameters.AddWithValue("#firstName", tbInfoFirstName.Text);
SavePersonInfo.Parameters.AddWithValue("#lastName", tbInfoLastname.Text);
SavePersonInfo.Parameters.AddWithValue("#age", tbInfoAge.Text);
SavePersonInfo.Parameters.AddWithValue("#city", tbInfoCity.Text);
SavePersonInfo.Parameters.AddWithValue("#contact", tbInfoKontakt.Text);
SavePersonInfo.Parameters.AddWithValue("#bio", tbInfoAbout.Text);
SavePersonInfo.Parameters.AddWithValue("#userName", loggedInUser);
ConnectDb.Open();
SavePersonInfo.ExecuteNonQuery();
//Response.Redirect("Manage.aspx");
ConnectDb.Close();
As said, the save code works on it's own, but not when the reading code is also active, eg: Not commented out.
I believe that the Page_Load event is launched before the event button on PostBack.
In this case the reading taken are the old data again filling the fields and finally recording the old data again.
Have you checked it?
If so, put your code in Page_Load in an if (IsPostBack!):
public void Page_Load() {
// ...
if (!IsPostBack) {
// code read the data
}
}

Auto retrieval of data in textbox

I have a log in page shown below
Admin only has a permission to access this page and he creates a new user with the following requirements.
when the particular user login his page is shown below
I need to retrieve the Faculty id,so that it should me automatically displayed in the textbox.
for that i need to call from datbase.? or is there any text box property to display the data ?
I am using asp.net withc#
SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
textBox.Text = Comm1.ExecuteScalar();
Conn.Close();

PrintToPrinter method for crystal reports throws logon exception

I am using PrintToPrinter(1,false,1,1) in my website for a crystal report . After I click on this button ( btnPrintToPrinter) it throws LogOnException and says Database Logon failed :
protected void btnPrintToPrinter_Click(object sender, EventArgs e)
{
int empno = Convert.ToInt32(Session["AnyVal"]);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string strQuery = "SELECT [View_EmplDetail].[Uni-Code], [View_EmplDetail].[FacultyCode], [View_EmplDetail].[EmpIDstr], [View_EmplDetail].[EngGivenName], [View_EmplDetail].[position_eng], [View_EmplDetail].[Emp_no], [View_EmplDetail].[GivenName], [View_EmplDetail].[position_name], [View_EmplDetail].[DariName], [Tbl_Dept].[EName], [View_EmplDetail].[photo] FROM [MoHEDatabase].[dbo].[View_EmplDetail] [View_EmplDetail] INNER JOIN [MoHEDatabase].[dbo].[Tbl_Dept] [Tbl_Dept] ON [View_EmplDetail].[DepCode]=[Tbl_Dept].[DepCode] WHERE [Emp_no] = #empno";
SqlCommand command = new SqlCommand(strQuery, connection);
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#empno", empno);
command.Connection = connection;
command.Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
ReportDocument rpt = new ReportDocument();
string _reportPath = Server.MapPath("..\\Student\\cardFinal.rpt");
//rpt.Load(AppDomain.CurrentDomain.BaseDirectory + "\\" + #"\\Student\\CardFinal.rpt");
rpt.Load(_reportPath);
rpt.SetDataSource(dt);
emp_card_report_viewer.ReportSource = rpt;
string sq = "";
//{View_OrgStr1.Uni-Code}=0 and {View_OrgStr1.FacultyCode}=119
//sq = "{View_StudentAddNew.Student_ID}=" + Session["AnyVal"];
if (Session["AnyVal"].ToString() != "")
{
sq = "{View_EmplDetail.Emp_no}=" + int.Parse(Session["AnyVal"].ToString());
}
//emp_card_report.Report.FileName = "../Student/CardFinal.rpt";
emp_card_report_viewer.SelectionFormula = sq;
//ConnectionInfo connInfo = new ConnectionInfo();
//connInfo.ServerName = "172.16.0.15";
//connInfo.DatabaseName = "MoHEMISDatabase";
//connInfo.UserID = "myuser";
//connInfo.Password = "myuser#sabir";
//TableLogOnInfos crtt = new TableLogOnInfos();
//TableLogOnInfo crtto = new TableLogOnInfo();
//Tables crtables;
//crtables = rpt.Database.Tables;
//foreach (CrystalDecisions.CrystalReports.Engine.Table crtable in crtables)
//{
// crtto = crtable.LogOnInfo;
// crtto.ConnectionInfo = connInfo;
// //crtable.ApplyLogInInfo(crtto);
//}
ConnectionInfo connInfo1 = new ConnectionInfo();
// connInfo1.ServerName = "server";
setDBLOGONforReport(connInfo1);
//emp_card_report_viewer.RefreshReport();
//ConnectionInfo connInfo = new ConnectionInfo();
//connInfo.ServerName = "server";
//connInfo.DatabaseName = "MoHEDatabase";
//connInfo.UserID = "hemis_admin";
//connInfo.Password = "hemis#sabir";
//setDBLOGONforReport(connInfo);
CrystalDecisions.Shared.PageMargins pageMargins = new
CrystalDecisions.Shared.PageMargins(0, 0, 0, 0);
rpt.PrintOptions.ApplyPageMargins(pageMargins);
rpt.PrintOptions.PrinterName = printerList.SelectedItem.Value;
emp_card_report_viewer.RefreshReport();
rpt.PrintToPrinter(1, false, 1, 1);
rpt.Close();
rpt = null;
}
error appears at : rpt.PrintToPrinter(1,falase,1,1);
any idea where it goes wrong ???
I have commented out some of the lines, just was checking on them ...
any help would be appreciated...tnx
Lucky, I suspect you don't mean "after I compile" that it throws the error. I'm assuming you mean "after I click my 'btnPrintToPrinter' button in my web application"? Whatever the case, please update the question to be more specific in how you trigger the error?
If your 'btnPrintToPrinter' button is sitting on the web page the moment you click it you get database logon failed, it is probably because you are doing two things that contradict each other:
1) You first assign a database as the report's datasource.
-THEN-
2) You are setting connection details for the report, i.e.
ConnectionInfo connInfo1 = new ConnectionInfo();
setDBLOGONforReport(connInfo1);
Remove these extra steps where you set connection info. The report doesn't need connection information if you are PUSHING a datatable to it. (Once you feed a report data it isn't going to connect to the server to get the data again.)
Note: IF you still see problems after you remove these lines. The issue is probably that the datatable you are passing is not what the report was build on in the first place. For example:
1) You built the report using a table named 'TableA' with 'field1', 'field2' and 'field3'.
2) Then you build a datatable in your code by querying 'TableA' with 'field1', 'field2' and 'fieldx' and 'fieldz'.
3) You pass the table from #2 into the report.
This can cause database logon errors (even though it's not really a logon problem). Because the report does this:
1) It TRIES to use the data you passed in. Then it CAN'T because the fields do not match what the report was designed from.
2) THEN the report, having no data, attempts to connect to the database server it WAS built on before.
3) Since you haven't (and should not) pass valid connection information to the report, it NOW throws 'database logon failed'.
So you see, it isn't really because the logon failed that you have a problem. It's because the data you provided (which makes the report NOT NEED to connect) was invalid data. As I said earlier, even one field being different can make the report fail. In fact, even just changing a single field's type (say varchar to int, or varchar(5) to nvarchar(10), etc.) can make the data you pass NOT match the data the report was built on.
So in your page load event (where I'm assuming you set
I have used this:
myReport.SetDatabaseLogon("username","password");
method and it solved the problem.

Sqldataapter advice

At present i have a the following code populating a datagridview showing the user account information on our system. What i want to do do is have a checkbox on the datagridview for the option "accountenabled" and a update button at the bottom of the form so it will update all users that have had changes made against them. I am currently pulling the data back using an sqldatareader however from what i have read i need to use a sqldataadapter. I`ve created the column names on the datagridview and the reader is currently pulling everything back correctly.
Could someone please point me in the right direction of doing this with an sqldatadapter?
Thanks
public UserAdmin()
{
InitializeComponent();
//Load user list
// Locals
Functionality func = new Functionality();
SqlConnection supportDB = null;
SqlCommand CheckUser = null;
SqlDataReader rdr;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string User = System.Environment.UserName.ToString();
string spName = "gssp_ShowAllUsers";
try
{
using (supportDB = new SqlConnection(GSCoreFunc.ConnectionDetails.getConnectionString(ConnectionType.SupportDB)))
{
using (CheckUser = new SqlCommand(spName, supportDB))
{
// Set the command type
CheckUser.CommandType = CommandType.StoredProcedure;
// Populate the parameters.
CheckUser.Parameters.Add(func.CreateParameter("#spErrorID", SqlDbType.Int, ParameterDirection.Output, DBNull.Value));
// Open the connection and populate the reader with the SP output
supportDB.Open();
rdr = CheckUser.ExecuteReader();
if (CheckUser.Parameters["#spErrorID"].Value != null)
{
throw new InvalidOperationException();
}
// If the data reader has rows display output on label
if (rdr.HasRows)
{
//Output values
while (rdr.Read())
{
//Bind to data table
dgvUsers.Rows.Add(rdr["agentID"].ToString(), rdr["createdon"].ToString(), rdr["firstname"].ToString(), rdr["lastname"].ToString(), rdr["username"].ToString(), rdr["emailaddress"].ToString(), rdr["Departments"].ToString(), rdr["accountenabled"].ToString(), rdr["AgentAccountLevel"].ToString());
}
}
// Close reader and connection.
rdr.Close();
supportDB.Close();
}
}
}
catch (Exception ex)
{
//Show error message
string error = ex.ToString(); //Real error
string FriendlyError = "There has been error loading the user list"; // Error user will see
GSCoreFunc.ShowMessageBox.msgBoxErrorShow(FriendlyError);
//Log error to ExceptionDB
GSCoreFunc.ReportException.reportEx(GSCoreFunc.ApplicationInformation.ApplicationName, error, FriendlyError, GSCoreFunc.ApplicationInformation.ComputerName, GSCoreFunc.ApplicationInformation.OperatingSystem, GSCoreFunc.ApplicationInformation.screenSize, GSCoreFunc.ApplicationInformation.IPAdddress, GSCoreFunc.ApplicationInformation.domainName);// Pass error to GSCoreFunc to log to the ExceptionDB
}
}
private void btClose_Click(object sender, EventArgs e)
{
//Close window
Close();
}
}
}
There is nothing wrong with using the SqlDataReader. The SqlDataAdapter is a higher level api that allows you to iterate through an SqlDataReader and store a copy of the results in a DataTable or a DataSet. This copy can then be used as the data source for your DataGridView.
One thing I would change with your code would be to use data binding instead of generating each row manually. If you set the DataSource property of the grid to either your SqlDataReader or to a DataTable filled by an SqlDataAdapter and then call the grids DataBind() method the grid should be filled automatically with your data.
To control the columns you would make sure your query only returns the required columns, and you would define the column setup in your aspx-file.
Using data binding is generally an easier and more flexible approach, so you should consider using that instead.
Look at this code
Initialize a sql adapter and fill with data source . Use a connection string other than using sql data source because it would be easy for customizing. :)

Categories