I am uploading a file to \temp\ but I want to access it through a hyperlink in a given column inside Access. I can successfully paste the string to the hyperlink field, but there´s no link between the string and the file itself.
I tried to copy paste a website address from a browser to Access, surprisingly the hyperlink is pasted along with the "string"
//upload arquivo
string conexaoAccess2 = ConfigurationManager.ConnectionStrings["conexaoAccess"].ToString();
using (OleDbConnection conexaodb1 = new OleDbConnection(conexaoAccess2))
{
conexaodb1.Open();
Random r = new Random();
int n = r.Next();
// pega somente nome
string[] f = camArq.Split('\\');
string fn = f[(f.Length) - 1];
string fullDest = #"C:\temp\" + nomeArqnoExt + n + fileExtension0;
string q = "UPDATE tbl_reg SET Campo1 = #campo WHERE nome_user = #nome1";
//copia arquivo para a pasta destino
File.Copy(camArq, fullDest, true);
//to save to the database
OleDbCommand cmd = new OleDbCommand(q, conexaodb1);
var parCamp = cmd.CreateParameter();
parCamp.ParameterName = "campo";
parCamp.DbType = DbType.String;
parCamp.Value = fullDest;
cmd.Parameters.Add(parCamp);
var parNome1 = cmd.CreateParameter();
parNome1.ParameterName = "nome1";
parNome1.DbType = DbType.String;
parNome1.Value = mdl.nome;
cmd.Parameters.Add(parNome1);
cmd.ExecuteNonQuery();
}
I expect the string to be copied as an hyperlink, nevertheless, there´s no DbType that assumes this type of data, is there? The actual results are: I can successfully paste the file path to the field, but the field contains no hyperlink to anything whatsoever:
Access Hyperlink type field requires value that is composed of 3 parts separated by # character: displaytext#path#subreference. Options:
If using Hyperlink type field in Access table design, include # characters in string to save.
Just use a text field to save path string without # characters then use FollowHyperlink method in code or format string to hyperlink structure with concatenation expression: "#" & [fieldname] & "#" - calculate in query or textbox ControlSource and set textbox IsHyperlink property to yes.
Related
I don't know if I am able to exactly explain my question but best of information that I am able to provide is following:
I have a datagrid view list of emails in it, I want to send emails to this list one by one and on the basis of the email (which is also a primary key), some information is fetched from the database and that fetched values should be replaced in my email body on specific places which are marked. It works perfectly when I enter all value manually but once I try to get values from the data grid view the values are displayed in the text fields (after getting fetched from the database) but when the email is sent, the required values are not replaced with the marked tags in my email body, as per my code tweaks, I have come to a conclusion that the value that I receive in the textbox from the database is dealt as a null value when passed to my email body. Here is my value passing code:
int cellValue = 0;
int rowCount = dgvStudents.Rows.Count;
for (int i = 0; i <= rowCount; i++)
{
string id = dgvStudents.Rows[i].Cells[cellValue].Value.ToString();
string campus = dgvStudents.Rows[i].Cells[cellValue + 1].Value.ToString();
txtStudentId.Text = id;
cmbStudyCenter.Text = campus;
}
**//And this is where the values are replaced with my marked tags:**
if (rdPreFinal.Checked)
{
string txtPreFinalText = txtEmailTemplate.Text.Replace("[ENTER VIVA TYPE HERE]", rdPreFinal.Text);
txtEmailTemplate.Text = txtPreFinalText;
}
else if (rdFinal.Checked)
{
string rdFinalText = txtEmailTemplate.Text.Replace("[ENTER VIVA TYPE HERE]", rdFinal.Text);
txtEmailTemplate.Text = rdFinalText;
}
else if (rdTestPhase.Checked)
{
string rdTestPhaseText = txtEmailTemplate.Text.Replace("[ENTER VIVA TYPE HERE]", rdTestPhase.Text);
txtEmailTemplate.Text = rdTestPhaseText;
}
string newDateTime = VivaDate.Text + " " + timeFormat.Text;
string newId = txtEmailTemplate.Text.Replace("[ENTER STUDENT ID]", txtStudentId.Text);
txtEmailTemplate.Text = newId;
string groupId = txtEmailTemplate.Text.Replace("[ENTER GROUP ID]", txtGroupId.Text);
txtEmailTemplate.Text = groupId;
string newDate = txtEmailTemplate.Text.Replace("[VIVA DATE/TIME]", newDateTime);
txtEmailTemplate.Text = newDate;
string newVivaStation = txtEmailTemplate.Text.Replace("[ENTER VIVA STATION DETAIL HERE ALONFWITH COMPLETE ADDRESS]", txtVivaStation.Text);
txtEmailTemplate.Text = newVivaStation;
//fetching previouus date and time for the viva
SqlConnection Connection = new SqlConnection(connectionString);
string commandText = "Select * from Sent_Viva_Emails where Student_Id ='" + txtStudentId.Text + "'";
SqlCommand Command = new SqlCommand(commandText, Connection);
Connection.Open();
SqlDataReader sdr1 = Command.ExecuteReader(); SqlConnection sql = new SqlConnection();
if (sdr1.Read())
{
string PreviousDate = sdr1.GetValue(6).ToString();
string PreviousTime = sdr1.GetValue(7).ToString();
PreviousDate = txtEmailTemplate.Text.Replace("[ENTER PREVIOUS VIVA DATE]", PreviousDate);
txtEmailTemplate.Text = PreviousDate;
PreviousTime = txtEmailTemplate.Text.Replace("[ENTER PREVIOUS VIVA TIME]", PreviousTime);
txtEmailTemplate.Text = PreviousTime;
}
I have searched StackOverflow and some other online platforms but could not get what I want. I hope I was able to explain my problem or experts can suggest me more changes to my questions to make it more understandable to answer.
Thank you :)
Simplified version of my question:
string newVivaStation = txtEmailTemplate.Text.Replace("[ENTER VIVA STATION DETAIL HERE ALONFWITH COMPLETE ADDRESS]", txtVivaStation.Text);
txtEmailTemplate.Text = newVivaStation;
on placing break points, I see value is passing through txtVivaStation.txtbut it never replaces in
[ENTER VIVA STATION DETAIL HERE ALONFWITH COMPLETE ADDRESS]
my email body. value from txtVivaStation.txt should be replaced with [ENTER VIVA STATION DETAIL HERE ALONFWITH COMPLETE ADDRESS] in my email body.
Here is SS of my result image after values are replaced
As you can see only date was replaced correctly with my marked tag but all other values were blank.
One Liner: value that are coming dynamically from the datagrid view to my textfields are not working but if I select enter values manually, it works fine.
Luckily I have found the exact issue with my problem after playing more with my code. The main issue was because the email body was loading into the form even before the dynamic values came from the database and that was the reason why my values were not able to replace the marked tags. Now I am simply loading my email template after all the values have been retrieved from the database and its working perfect, thank you for your comments and precious time!
I'm trying to make a query in Access 2010, but it keeps giving me this error "Data type mismatch in criteria expression." over the line "dataCommand.ExecuteNonQuery();"
String sql1 = "INSERT INTO Formulario (Numero, Localidad, [Parroquia o Institucion], Fecha, [Id Institucion], Comunitaria, Observacion) VALUES (#Numero, #Localidad, [#Parroquia o Institucion], #Fecha, [#Id Institucion], #Comunitaria, #Observacion)";
mi_conexion.Open();
//insertar tabla formulario...........
dataCommand.CommandText = sql1;
dataCommand.Parameters.Add("#Numero", OleDbType.VarChar).Value = numero;
dataCommand.Parameters.Add("#Localidad", OleDbType.VarChar).Value = textBox_localidad.Text;
dataCommand.Parameters.Add("#Parroquia o Institucion", OleDbType.VarChar).Value = comboBox_instituciones.Text;
dataCommand.Parameters.AddWithValue("#Fecha", "#" + fecha.Value.Date.Day.ToString() + "/" + fecha.Value.Date.Month.ToString() + "/" + fecha.Value.Date.Year.ToString() + "#");
dataCommand.Parameters.Add("#Id Institucion", OleDbType.VarChar).Value = Int32.Parse(label_id2.Text);
dataCommand.Parameters.Add("#Observacion", OleDbType.VarChar).Value = obs;
if(radioButton_comunitaria.Checked)
{
dataCommand.Parameters.Add("#Comunitaria", OleDbType.VarChar).Value = true;
}
else
{
dataCommand.Parameters.Add("#Comunitaria", OleDbType.VarChar).Value = false;
}
dataCommand.ExecuteNonQuery();
I dont know what could be the reason.....
I tried this:
String sql1 = "INSERT INTO Formulario (Numero, Localidad, ParroquiaoInstitucion, Fecha, IdInstitucion, Comunitaria, Observacion) VALUES (?,?,?,?,?,?,?)";
mi_conexion.Open();
//insertar tabla formulario...........
dataCommand.CommandText = sql1;
dataCommand.Parameters.AddWithValue("Numero", numero);
dataCommand.Parameters.AddWithValue("Localidad", textBox_localidad.Text);
dataCommand.Parameters.AddWithValue("ParroquiaoInstitucion", comboBox_instituciones.Text);
dataCommand.Parameters.AddWithValue("Fecha", "#" + fecha.Value.Date.Day.ToString() + "/" + fecha.Value.Date.Month.ToString() + "/" + fecha.Value.Date.Year.ToString() + "#");
dataCommand.Parameters.AddWithValue("IdInstitucion", Int32.Parse(label_id2.Text));
if(radioButton_comunitaria.Checked)
{
dataCommand.Parameters.AddWithValue("Comunitaria", true);
}
else
{
dataCommand.Parameters.AddWithValue("Comunitaria", false);
}
dataCommand.Parameters.AddWithValue("Observacion", obs);
dataCommand.ExecuteNonQuery();
But it doesn't work yet -_-.....
Use AddWithValue instead of Add method. Sql Server will decide what type is the data for you ! I'm giving you an example. Also OLE DB does not support named parameters, only unnamed parameter
dataCommand.Parameters.AddWithValue("?", true);
You should set the parameters in the right order. Here is the source how to add parameters for OleDb in MSDN
Access database (even when OleDb is in action) does not know parameters which names start with #.
To be able to use parameters with MS Access database engine, use:
PARAMETERS [parameter1] type, [parameter2] type, [parameterN] type;
SELECT <FieldList>
FROM <TableName>
WHERE FieldName = [parameter1] AND ...
For further information, please see: PARAMETERS Declaration (Microsoft Access SQL)
Second way is to use non-named parameters:
SELECT <FieldList>
FROM <TableName>
WHERE FieldName = ? AND FieldName2 =?
But i prefer to use named parameters.
OleDb wants that you add your parameters in the same order in which their placeholder appears in the command text. OleDb using Ms-Access accepts also parameters with name that starts with # without problem (probably to ease the upsizing to Sql Server), but you should absolutely respect the order.
In your code you add the parameter for the field Comunitaria after the parameter for the field Observacion This creates the mismatch problem because OleDb passes the value for Comunitaria to the field Observacion and viceversa. The field Comunitaria then receives a value that cannot be converted to a boolean (Yes/No) value.
Try to change your code in this way
if(radioButton_comunitaria.Checked)
{
dataCommand.Parameters.Add("#Comunitaria", OleDbType.VarChar).Value = true;
}
else
{
dataCommand.Parameters.Add("#Comunitaria", OleDbType.VarChar).Value = false;
}
dataCommand.Parameters.Add("#Observacion", OleDbType.VarChar).Value = obs;
dataCommand.ExecuteNonQuery();
A part from this you should remove that spaces inside the parameters names. It could only give you troubles and it is not needed.
I suggest also to use a correct datatype for the Fecha field. If Access expects a Date don't try to build a replacement string like you are doing the insert inside the Access interface.
dataCommand.Parameters.AddWithValue("#Fecha", new DateTime(fecha.Value.Date.Year,
fecha.Value.Date.Month,
fecha.Value.Date.Day)
I have the following code which iterates through a CSV file and writes to the SQL table:
foreach (string line in lines.Skip(1))
{
var sqlfmt = "INSERT INTO [" + tab + "] values ({0})";
var insert = string.Format(sqlfmt, line.Replace("\"", "'"));
MessageBox.Show(insert + "");
SqlCommand ty = new SqlCommand(insert, myConnection);
ty.ExecuteNonQuery();
}
The issue I have now is if one of the column has ' in the text my application crashes.
What would be the best way to avoid the issue?
Just change
var insert = string.Format(sqlfmt, line.Replace("\"", "'"));
To:
var insert = string.Format(sqlfmt, line.Replace("'", "''").Replace("\"", "'"));
The reason for this is that in T-SQL (SQL Server's version of SQL), single-quotes inside a string are escaped by another single quote. For example, if you wanted to properly quote the string Bob's quotes', the properly-escaped SQL string would be 'Bob''s quotes'''.
Greetings from Appdev (i'm new to Crystall Report)
I was Creating a web application which will contains a crystal report.
My Requirement is:
The report should be displayed Based on the value (textbox in web form) which is given in textbox.
Eg:
if Textbox value = 2 means only the item which has id 2 should only get display.
My crystal report has 3 sub Reports like cheque,Party(which also contains values from other table called voucher) and finally bank.
these 4 tables are linked by 1 common field called id.
need to know how to pass parameter to crystall report.
How to display the result only once (my code display same result twice)
this is how i bind the crystal report using parameters from .cs file in c#
public void LoadTransReceipt()
{
string Date = "";
string Sql = "SELECT tREC_NUPKId as ID from TB_TransReceipt where tREC_VCVoucherNo='" + TXTVou.Text.Trim() + "' and tREC_NUIsActive=1";
SqlDataReader rdr = mobjGenlib.objDBLib.ExecuteQueryReader(Sql.ToString());
while (rdr.Read())
{
Session["ID"] = rdr.GetValue(0).ToString();
}
rdr.Close();
if (!string.IsNullOrEmpty(Session["ID"] as string))
{
if (Session["Date"] != null)
{
Date = mobjGenlib.ConvertString(Session["Date"]);
}
reportPath = GetReportPath("ReceiptReport.rpt");
CRReport = new ReportDocument();
CRReport.Load(reportPath);
CrystalReportViewer1.ReportSource = CRReport;
AddParameterToReport("IDP", Session["ID"].ToString());
AddParameterToReport("ActiveP", 1);
AddParameterToReport("IDB", Session["ID"].ToString());
AddParameterToReport("ActiveB", 1);
AddParameterToReport("IDC", Session["ID"].ToString());
AddParameterToReport("ActiveC", 1);
// ConnectionInfo connectionInfo = ConnInfo();
ConnectionInfo objConnInfo = new ConnectionInfo();
objConnInfo.DatabaseName = "Demo";
objConnInfo.UserID = "aa";
objConnInfo.Password = "aaaa";
objConnInfo.ServerName = "HOME-PC\\SQLEXPRESS";
SetDBLogonForReport(objConnInfo, CRReport);
SetDataSetForMultipleSubReport(objConnInfo, CRReport);
}
}
but when i execute the code it displaying all data's available in table with double time like shown below
can any one help me to solve this issue
Thanks in advance
getting error as
" **
Specified argument was out of the range of valid values
**"
From Field Explorer in the report right click add new parameter, then in code behind you have to set the value of the parameter like:
CRReport.SetParameterValue("#Parameter", TXTVou.Text)
You can prevent the duplication by add the word DISTINCT to your Query like:
"SELECT DISTINCT tREC_NUPKId as ID from TB_TransReceipt where tREC_VCVoucherNo='" + TXTVou.Text + "' and tREC_NUIsActive=1"
or You can prevent the duplication by (Suppress If Duplicated) property in the field
Okay, so here is the problem, i get a "Data type mismatch in criteria expression." when attempting a certain code to update my access database.
the update part is :
<%if (Request.Form["CmdEnregistrer"] != null)
{
cnx.Open();
string sql1;
string mat;
string nom;
string adr;
string sexe;
string ema;
string tel;
for (int bo = 1; bo < tmp; bo++)
{
mat = Request.Form["matricule"+bo];
nom = Request.Form["nom" + bo];
adr = Request.Form["adresse" + bo];
sexe = Request.Form["sexe" + bo];
ema = Request.Form["email" + bo];
tel = Request.Form["tel" + bo];
sql1 = "Update Enseignant Set nom='"+nom+"',adresse='"+adr+"',sexe='"+sexe+"',email='"+ema+"',tel='"+tel+"' where matricule='"+int.Parse(mat)+"'";
OleDbCommand cmd1 = new OleDbCommand(sql1, cnx);
cmd1.ExecuteNonQuery();
} cnx.Close();
}%>
I've already ran tests on the mat/nom/adr.. strings to see if they received the correct content and it seems that way...
My database is set as : matricule is AutoIncrement Number, and the rest (nom/adr/..) is Text.
Any help please?
Take a look here:
where matricule='"+int.Parse(mat)+"'";
Evaluates to:
where matricule='5' // just an example
It's probably treating your "5" as a string. Try changing that to:
where matricule="+int.Parse(mat);
It'd also be a good thing to look into parameterizing your query. It's safer and makes the sql statement easier to maintain too.