I have a webform in which i am calling a function DropDown() from a .cs file
Reference:same as my friend ishan posted on Calling a C# function in asp.net
I am getting the error as:
Error 1 'DropDown' does not contain a
definition for 'DropDown' and no
extension method 'DropDown' accepting
a first argument of type 'DropDown'
could be found (are you missing a
using directive or an assembly
reference?)
aspx.cs code as follows:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Collections;
using System.IO;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DropDown abs =new DropDown(this.DropDownList2,this.DropDownList3);
abs.DropDown();
}
//*******On click of GO
public void Button1_Click(object sender, EventArgs e)
{
Button4.Visible = true;
String dbDate = DateTime.ParseExact(TextBox3.Text, "dd/mm/yyyy", null).ToString("yyyy-mm-dd");
String respo1 = "";
String respo2 = "";
String editorcont1 = "";
int res = 0;
String sb = "";
String petitioner = "";
String petitioner1 = "";
String resp = "";
String resp1 = "";
String respondants = "";
String addr1 = "";
String addr2 = "";
var order = "";
String nextdate = "";
String nextdate1 = "**/**/****";
String judge1 = "";
String judge2 = "";
String judge3 = "";
String a = DropDownList1.SelectedItem.Value;
String b = DropDownList3.SelectedItem.Value.PadLeft(3, '0');
String c = TextBox1.Text.PadLeft(5, '0').ToString();
String d = TextBox2.Text.ToString();
String digit = a + b + c + d;
String jjj = "";
try
{
OdbcConnection casetype = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=10.155.160.130;Database=testcase;User=root;Password=;Option=3;");
casetype.Open();
String petresquery1 = "select fil_no from testcase.main where reg_no =? OR fil_no=?";
OdbcCommand petrescmd1 = new OdbcCommand(petresquery1, casetype);
petrescmd1.Parameters.AddWithValue("?", digit);
petrescmd1.Parameters.AddWithValue("?", digit);
OdbcDataReader respetMyReader1 = petrescmd1.ExecuteReader();
while (respetMyReader1.Read())
{
String fil_no = respetMyReader1["fil_no"].ToString();
HiddenField4.Value = fil_no;
//Response.Write(HiddenField4.Value);
}
string showmodifquery = "select notice from notice_aspx where fil_no=?";
OdbcCommand showmodifcmd = new OdbcCommand(showmodifquery, casetype);
showmodifcmd.Parameters.AddWithValue("?", HiddenField4.Value);
OdbcDataReader showmodifMyReader = showmodifcmd.ExecuteReader();
if (showmodifMyReader.Read())
{
String showmodif1 = showmodifMyReader["notice"].ToString();
Editor1.Content = showmodif1;
}
else
{
//************to get case type
string casetypequery = "select casename from casetype where skey=?";
//************to get pet res
string petresquery = "select pet_name,res_name from testcase.main where reg_no =? OR fil_no=?";
//*******to get respondants
string respoquery = "SELECT sr_no,partyname,addr1,addr2 FROM testcase.party where fil_no=? and pet_res='R'order by sr_no,party_lh,party_lh2,party_lh3,party_lh4,party_lh5";
//*******to get order
string ordequery = "select orde from testcase.orddetpabak where fil_no=? and orderdate=?";
//*********to get next date
string nextdatequery = "SELECT next_dt FROM testcase.heardt where fil_no=? and next_dt>?;";
//*********to get jud1
string jud1query = "select jname from testcase.orddetpabak,testcase.judge where orddetpabak.jud1 = judge.jcode and fil_no=? and orderdate=?;";
//*********to get jud2
string jud2query = "select jname from testcase.orddetpabak,testcase.judge where orddetpabak.jud2 = judge.jcode and fil_no=? and orderdate=?;";
//*********to get jud3
string jud3query = "select jname from testcase.orddetpabak,testcase.judge where orddetpabak.jud3 = judge.jcode and fil_no=? and orderdate=?;";
//************to get case type
OdbcCommand casetypecmd = new OdbcCommand(casetypequery, casetype);
String casetypefromdropdown = DropDownList3.SelectedItem.ToString();
casetypecmd.Parameters.AddWithValue("?", casetypefromdropdown);
using (OdbcDataReader casetypeMyReader = casetypecmd.ExecuteReader())
{
while (casetypeMyReader.Read())
{
String casename = casetypeMyReader["casename"].ToString();
HiddenField1.Value = casename;
}
}
//************to get pet res
OdbcCommand petrescmd = new OdbcCommand(petresquery, casetype);
petrescmd.Parameters.AddWithValue("?", digit);
petrescmd.Parameters.AddWithValue("?", digit);
using (OdbcDataReader respetMyReader = petrescmd.ExecuteReader())
{
while (respetMyReader.Read())
{
petitioner1 = respetMyReader["pet_name"].ToString();
//petitioner1 = petitioner.Substring(0, 1) + petitioner.Substring(1).ToLower();
resp1 = respetMyReader["res_name"].ToString();
//resp1 = resp.Substring(0, 1) + resp.Substring(1).ToLower();
//String fil_no = respetMyReader["fil_no"].ToString();
//HiddenField4.Value = fil_no;
////Response.Write(HiddenField4.Value);
}
if (petitioner1 == "")
{
Response.Write("<b><font color='red'>Wrong Entry!!!");
}
}
//*******to get respondants
String respo = HiddenField4.Value;
OdbcCommand respocmd = new OdbcCommand(respoquery, casetype);
respocmd.Parameters.AddWithValue("?", respo);
using (OdbcDataReader respoMyReader = respocmd.ExecuteReader())
{
while (respoMyReader.Read())
{
respo1 = respoMyReader["sr_no"].ToString();
respo2 = respoMyReader["partyname"].ToString();
addr1 = respoMyReader["addr1"].ToString();
addr2 = respoMyReader["addr2"].ToString();
res = Convert.ToInt32(respo1);
//Response.Write(res);
//Response.Write(respo2);
//editorcont1 = "<table><tr><td width='10'>" + res + "</td><td>"+"<P align= 'left'>"+ respo2 +"</P></td>"+"</br>";
////HiddenField7.Value = editorcont1;
//asd(editorcont1);
//respondants = respo2.Substring(0, 1) + respo2.Substring(1).ToLower();
//addr1 = addr1.Substring(0, 1) + addr1.Substring(1).ToLower();
//addr2 = addr2.Substring(0, 1) + addr2.Substring(1).ToLower();
editorcont1 = res + ") " + respo2 + "<br/> " + addr1 + " " + addr2 + "<br/>";
sb = sb + editorcont1;
}
}
//*******to get order
OdbcCommand ordecmd = new OdbcCommand(ordequery, casetype);
ordecmd.Parameters.AddWithValue("?", HiddenField4.Value);
ordecmd.Parameters.AddWithValue("?", dbDate);
using (OdbcDataReader ordeMyReader = ordecmd.ExecuteReader())
{
while (ordeMyReader.Read())
{
order = ordeMyReader["orde"].ToString();
}
}
//*******to get nextdate
OdbcCommand nextdatecmd = new OdbcCommand(nextdatequery, casetype);
nextdatecmd.Parameters.AddWithValue("?", HiddenField4.Value);
nextdatecmd.Parameters.AddWithValue("?", dbDate);
using (OdbcDataReader nextdateMyReader = nextdatecmd.ExecuteReader())
{
while (nextdateMyReader.Read())
{
nextdate = nextdateMyReader["next_dt"].ToString();
}
nextdate1 = Convert.ToDateTime(nextdate).ToString("dd/MM/yyyy");
}
//*********to get jud1
OdbcCommand jud1cmd = new OdbcCommand(jud1query, casetype);
jud1cmd.Parameters.AddWithValue("?", HiddenField4.Value);
jud1cmd.Parameters.AddWithValue("?", dbDate);
using (OdbcDataReader jud1MyReader = jud1cmd.ExecuteReader())
{
while (jud1MyReader.Read())
{
judge1 = jud1MyReader["jname"].ToString();
jjj = "J";
}
}
//*********to get jud2
OdbcCommand jud2cmd = new OdbcCommand(jud2query, casetype);
jud2cmd.Parameters.AddWithValue("?", HiddenField4.Value);
jud2cmd.Parameters.AddWithValue("?", dbDate);
using (OdbcDataReader jud2MyReader = jud2cmd.ExecuteReader())
{
while (jud2MyReader.Read())
{
judge2 = jud2MyReader["jname"].ToString();
jjj = "JJ";
}
}
//*********to get jud3
OdbcCommand jud3cmd = new OdbcCommand(jud3query, casetype);
jud3cmd.Parameters.AddWithValue("?", HiddenField4.Value);
jud3cmd.Parameters.AddWithValue("?", dbDate);
using (OdbcDataReader jud3MyReader = jud3cmd.ExecuteReader())
{
while (jud3MyReader.Read())
{
judge3 = jud3MyReader["jname"].ToString();
jjj = "JJJ";
}
}
String tyear = TextBox2.Text;
tyear = tyear.Remove(0, 2);
String year = DateTime.Now.Year.ToString();
year = year.Remove(0, 2);
TextBox4.Text = order;
string editorcontents =
" No. J/" + DropDownList3.SelectedItem + "-" + TextBox1.Text + "-" + tyear + "/" + " " + "/" + year +
"<br/>" + " Date:" + DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year +
"<br/>" + "<P align='center'><b> IN THE HIGH COURT OF BOMBAY AT GOA </b></P>" +
"<P align='center'><b>PANAJI GOA</font></b></P>" +
"<br/>" + "<P align='center'><u><b>" + HiddenField1.Value + " NO. " + TextBox1.Text + " OF " + TextBox2.Text + "</b></u></P>" +
"<P align='center'><font size=3>(Under Article 227 of the Constitution of India)</font> </P>" +
"<br />" +
"<table><tr><td width='750px'><p align='left'>" + petitioner1 + "</p>" + "</td><td>" + "<p align='right'>" + "..Petitioner" + "</p>" + "</td></tr>" + "<tr><td><p align='center'>" + "V/s" + "</p>" + "</td><td></td>" + "</tr>" + "<tr><td width='75px'><p align='left'>" + resp1 + "</p>" + "</td><td>" + "<p align='right'>" + "..Respondent" + "</p>" + "</td></tr></table>" +
//"<p align='left'>" + petitioner1 + "<p align='right'>" + "...petitioner"+"</p>"+
"<br/>" + "<P align= 'left'>From" +
"<br/>" + "Assistant Registrar," +
"<br/>" + "High Court Of Bombay at Goa Panaji Bench</P>" +
"<br/>" + "<P align= 'left'>To,</P>" +
"<br/>" + sb + "</br>" +
"<br/>" + "<P align= 'left'>Sir,</P></br>" +
"<P align='justify'> " + "The Petitioner abovenamed having presented a Petition to this Court under Article 227 of the Constitution of India, praying for reliefs as stated in the accompanying copy of the petition and the same having been registered in this Court as Writ Petition and this Court, having on the " +
"<font color='#0000FF'>" + TextBox3.Text + "</font>" + " ordered to issue notice, I have the honour to inform you that the matter will come up for " +
"<b><u>" + "admission on " + "<font color='#0000FF'>" + nextdate1 + "</font>" + " at 10.30 a.m. or thereafter on any day as per the convenience of this Court," + "</u></b>" +
"and that if no appearance is made on your behalf either in person or by an Advocate of this Court or an agent duly authorized and instructed by you, it will be heard and determined in your absence." + "</P>" +
"<br/><P align='center'>" + "Coram : " + judge1 + ", " + judge2 + ", " + judge3 +jjj+ "</P>" +
"<br/>" +
" <P align='justify'>" + order.Replace(Environment.NewLine, "<br /> ") + "</P>" +
"<br/><br/>" + "<P align= 'right'>" + "By Order of the Court,".Replace(Environment.NewLine, "<br/>") + "</P>" +
"<br/><br/>" + "<P align= 'right'>( G. M. Redker ) " +
"<br/>" + "Assistant Registrar " +
"<br/>" + "High Court of Bombay" +
"<br/>" + "Panaji Bench (Goa) " + "</P>" +
"<br/><P align='left'>" + "Enclosure :-" + " (i)Copy Of Petition" + "</P>" +
"<br/><P align='left'>" + " (ii)" + "</P>" +
"<br/><P align='left'>" + " (iii)" + "</P>" +
"<br/><P align='justify'> " + "N.B. :- Attention is invited to Rules 11 and 13, Chapter XVII of the High Court Appellate Side Rules, 1960, which reads as follows :-" + "</P>" +
"<br/><P align='justify'> " + "Rule 11 :- An answer to the rule nisi showing cause against such application shall be made by filing an affidavit in the Office of the Registrar and by serving a copy thereof upon the applicant or his Advocate or attorney, as the case may be, at least two days before the returnable date of the rule." + "</P>" + "<br/><P align='justify'> " + "Rule 13 :- No further affidavit or affidavits shall be filed by any party except with the leave of the Court." + "</P>" +
"<br/><p align='left'>" + "ep/-" +
"<BLOCKQUOTE style='page-break-before: always'>xdfghfdhgrfgbx blah</BLOCKQUOTE>";
Editor1.Content = editorcontents;
string editorcont2 = " No. J/" + DropDownList3.SelectedItem + "-" + TextBox1.Text + "-" + tyear + "/" + " " + "/" + year +
"<br/>" + " Date:" + DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year +
"<br/> <br/>" + "<P align='center'><b> IN THE HIGH COURT OF BOMBAY AT GOA " +
"<br/>" + " PANAJI BENCH </b></P>" +
"</br>" + "<P align='center'>" + "<u><b>" + HiddenField1.Value + " NO. " + TextBox1.Text + " OF " + TextBox2.Text + " </P>" + "</b></u>" +
"<br/> <br/>" + "<P align='justify'> From," +
"<br/>" + " The ASSISTANT REGISTRAR " +
"<br/>" + " High Court of Bombay at Goa" +
"<br/>" + " Panaji Bench </P>" +
"<br/> <br/>" + "<P align='justify'> To," +
"<br/>" + " The Registrar," +
"<br/>" + " City Civil Court " +
"<br/>" + " Bangalore </P>" +
"<br/> <br/>" + "<P align='left'> Sir, </P>" +
"<br/>" + "<P align='justify'> " + "I have the honour to forward herewith the accompanying notice alongwith copy of petition for service on the Respondent No. 2 in the case noted above and to request you to be so good as to arrange to serve the Original copy and to return the office copy to this Court duly served AT THE EARLIEST by causing the Original notice to be delivered to the Respondent No. 2 and by obtaining the acknowledgement on the Office Copy. If the said notice does not fall under your jurisdiction, kindly forward the same to the Court under whose jurisdiction it comes, under intimation to this office. Service Report may please be translated to English, if written in any other language. </p>" +
"<br/><br/>" + "<P align= 'right'>" + "By Order of The Court," +
"<br/><br/>" + "( G. M. Redker ) " +
"<br/>" + "Assistant Registrar " +
"<br/>" + "High Court of Bombay" +
"<br/>" + "Panaji Bench (Goa) </P>" +
"<br/> <P align='left'>Encl. " +
"<br/> rc/- </P>";
Editor2.Content = editorcont2;
}
}
catch (Exception er)
{ }
}
protected void Button2_Click(object sender, EventArgs e)
{
String dbDate = DateTime.ParseExact(TextBox3.Text, "dd/mm/yyyy", null).ToString("yyyy-mm-dd");
//Extract data from Page (pd).
//Label16.Text = Editor1.Content; // Attribute
// makae ready HttpContext
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
// Create PDF document
Document pdfDocument = new Document(PageSize.A4, 80, 50, 30, 65);
PdfWriter wri = PdfWriter.GetInstance(pdfDocument, new FileStream("d://" + HiddenField1.Value + HiddenField4.Value + dbDate + ".pdf", FileMode.Create));
PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream);
pdfDocument.Open();
string htmlText = Editor1.Content;
//string htmlText = htmlText1.Replace(Environment.NewLine, "<br/>");
System.Collections.Generic.List<IElement> htmlarraylist = HTMLWorker.ParseToList (new StringReader(htmlText), null);
//Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
//pdfDocument.Add(paragraph);
for (int k = 0; k < htmlarraylist.Count; k++)
{
pdfDocument.Add((IElement)htmlarraylist[k]);
}
//***********FORWARDING LETTER
pdfDocument.NewPage();
string htmlText2 = Editor2.Content;
System.Collections.Generic.List<IElement> htmlarraylist2 = HTMLWorker.ParseToList(new StringReader(htmlText2), null);
for (int k = 0; k < htmlarraylist2.Count; k++)
{
pdfDocument.Add((IElement)htmlarraylist2[k]);
}
pdfDocument.Close();
HttpContext.Current.Response.End();
}
protected void Button3_Click(object sender, EventArgs e)
{
String dbDate = DateTime.ParseExact(TextBox3.Text, "dd/mm/yyyy", null).ToString("yyyy-mm-dd");
OdbcConnection MyConnection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=10.155.160.130;Database=testcase;User=root;Password=;Option=3;");
MyConnection.Open();
String MyString = "select notice from notice_aspx where fil_no=? and orderdate=?";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
MyCmd.Parameters.AddWithValue("", HiddenField4.Value);
MyCmd.Parameters.AddWithValue("", dbDate);
using (OdbcDataReader MyReader4 = MyCmd.ExecuteReader())
{
//**
if (MyReader4.Read())
{
String MyString1 = "UPDATE notice_aspx SET notice=? where fil_no=? AND orderdate=?";
OdbcCommand MyCmd1 = new OdbcCommand(MyString1, MyConnection);
MyCmd1.Parameters.AddWithValue("", Editor1.Content.ToString());
MyCmd1.Parameters.AddWithValue("", HiddenField4.Value.ToString());
MyCmd1.Parameters.AddWithValue("", dbDate);
MyCmd1.ExecuteNonQuery();
}
else
{
// set the SQL string
String strSQL = "INSERT INTO notice_aspx (fil_no,notice,orderdate) " +
"VALUES (?,?,?)";
// Create the Command and set its properties
OdbcCommand objCmd = new OdbcCommand(strSQL, MyConnection);
//Response.Write("****"+HiddenField4.Value);
objCmd.Parameters.AddWithValue("", HiddenField4.Value.ToString());
objCmd.Parameters.AddWithValue("", Editor1.Content.ToString());
objCmd.Parameters.AddWithValue("", dbDate);
// execute the command
objCmd.ExecuteNonQuery();
}
}
}
protected void Button4_Click(object sender, EventArgs e)
{
}
protected void Button4_Click1(object sender, EventArgs e)
{
Editor2.Visible = true;
}
}
.CS code as follows
Please refer:
Calling a C# function in asp.net
How to solve the issue.
I don't quite see what your trying to do (source code of class DropDown would help), but:
The class DropDown cannot have a method called DropDown(). This name is reserved for constructors, so you can call it only like this:
var dd = new DropDown();
You cannot call the constructor of a class like an instance-method, therefore this line gives an error:
abs.DropDown();
If this is a method you want to call, then rename the method to something different (difficult to suggest a good name without knowing what the method should do).
refer to ishan thread Calling a C# function in asp.net. Modify your dropdown class, and call some other method like register in given example
You are trying to call DropDown method from object of type DropDown. What's it?
Related
First time post as I'm a bit stuck here.
I am using this code to return some rows from a SQL Server database:
public static SqlDataReader SQLSelect(string sqlcommand, string[,] parameters, int length)
{
try
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
SqlDataReader reader;
SqlCommand cmd = new SqlCommand(sqlcommand, conn);
var allLength = parameters.Length;
for (int i = 0; i < parameters.Length - length; i++)
{
string paramid = parameters[i, 0];
if (paramid == "#date" || paramid == "#Date" || paramid == "#DATE")
{
string paramvalue = parameters[i, 1];
DateTime date = Convert.ToDateTime(paramvalue);
paramvalue = date.ToString("yyyy-MM-dd HH':'mm':'ss");
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
else
{
string paramvalue = parameters[i, 1];
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
return reader;
}
catch
{
return null;
}
}
This function is called like so
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
now all runs fine except the reader only contains 13 rows of data where as the actual query being
exec sp_tblstudentprogress_selectforprinting #studentid=N'87'
as an example, returns 91 rows.
I'm at a loss as to why this is the case. Only thing I have noticed is when using SQL Server profiler, running the query from SQL Server, there is a RPC: Started and Completed, as for running from withing my web app, there is only an RPC: Started.
Any thoughts on this?
EDIT:
here is how I enumerate the reader
protected void btnPrint_Click(object sender, EventArgs e)
{
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
string firstname = txtFirstName.Text;
string lastname = txtLastName.Text;
int i=0;
string[] heading1 = new string[reader.FieldCount];
string[] heading2 = new string[reader.FieldCount];
string[] log = new string[reader.FieldCount];
try
{
while (reader.Read())
{
heading1[i] = "Progress Log for: Block: " + reader["block"].ToString() + " Lesson: " + reader["lesson"].ToString();
heading2[i] = "";
log[i] =
/*"PROGRESS LOG for " + reader["firstname"].ToString() + " " + reader["lastname"].ToString() + " Printed on " + DateTime.Today.ToShortDateString() + Environment.NewLine +*/
Environment.NewLine +
"Teacher: " + reader["teacher"].ToString() + Environment.NewLine +
"Date: " + reader["date"].ToString() + Environment.NewLine +
"Year: " + reader["year"].ToString() + Environment.NewLine +
"Block: " + reader["block"].ToString() + Environment.NewLine +
"Lesson: " + reader["lesson"].ToString() + Environment.NewLine +
"Warm Up: " + reader["warmup"].ToString() + Environment.NewLine +
"Range: " + reader["range"].ToString() + Environment.NewLine +
"Technique Sheet: " + reader["techniquesheet"].ToString() + Environment.NewLine +
"Technique Other: " + reader["techniqueother"].ToString() + Environment.NewLine +
Environment.NewLine +
"Notes: " + reader["notes"].ToString() + Environment.NewLine +
Environment.NewLine +
"Mark: " + reader["mark"].ToString()+ Environment.NewLine ;
i++;
}
}
catch
{
}
finally
{
if (Common.conn != null)
{
Common.conn.Close();
}
}
Common.PDFCreateProgressLog("Progress log for: " + firstname + " " + lastname, "Progress log for: " + firstname + " " + lastname, "PDF_" + firstname + " " + lastname + "-" + DateTime.Today.ToString("yyyy-MM-dd") + ".pdf", "Progress log for: " + firstname + " " + lastname, log, heading1, heading2);
}
You are confusing the meaning of the FieldCount property. It identifies the number of Columns, not the number of Rows. You cannot determine the total number of rows from a streaming source like a Reader, without enumerating all of the rows first (at least once, anyway).
So you will need to extend your arrays each time (lists might be easier for this) you read a row from the Reader and test the Reader to se when there are no more rows.
I am trying to create a database here, I am able to create it with just a single word like "test" or "example". However, when i tried to create a database name, 2 words with a spacing in the middle for example "testing table" , it does not create the database. I tried [],'' and {} but it did not worked. Here is my code.
str = "CREATE DATABASE "+textBox1.Text+" ON PRIMARY " +
"(NAME = "+textBox1.Text+"_Data, " +
"FILENAME = 'C:\\"+textBox1.Text+".mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = "+textBox1.Text"+_Log, " +
"FILENAME = 'C:\\"+textBox1.Text"+.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
From this article Create a SQL Server database using C#, you could try sanitizing your input, for example:
private void button2_Click(object sender, System.EventArgs e)
{
DatabaseParam DBParam = new DatabaseParam();
DBParam.DatabaseName = textBox1.Text;
//Assign Data file parameters
DBParam.DataFileGrowth = "10%";
DBParam.DataFileName = textBox3.Text;
DBParam.DataFileSize = "2";//2MB at the init state
DBParam.DataPathName = textBox2.Text;
//Assign Log file parameters
DBParam.LogFileGrowth = "10%";
DBParam.LogFileName = textBox10.Text;
DBParam.LogFileSize = "1";//1MB at the init state
DBParam.LogPathName = textBox11.Text;
CreateDatabase(DBParam);
}
private void CreateDatabase(DatabaseParam DBParam)
{
System.Data.SqlClient.SqlConnection tmpConn;
string sqlCreateDBQuery;
tmpConn = new SqlConnection();
tmpConn.ConnectionString = "SERVER = " + DBParam.ServerName + "; DATABASE = master; User ID = sa; Pwd = sa";
sqlCreateDBQuery = " CREATE DATABASE " + DBParam.DatabaseName + " ON PRIMARY "
+ " (NAME = " + DBParam.DataFileName +", "
+ " FILENAME = '" + DBParam.DataPathName +"', "
+ " SIZE = 2MB,"
+ " FILEGROWTH =" + DBParam.DataFileGrowth +") "
+ " LOG ON (NAME =" + DBParam.LogFileName +", "
+ " FILENAME = '" + DBParam.LogPathName + "', "
+ " SIZE = 1MB, "
+ " FILEGROWTH =" + DBParam.LogFileGrowth +") ";
SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
try
{
tmpConn.Open();
MessageBox.Show(sqlCreateDBQuery);
myCommand.ExecuteNonQuery();
MessageBox.Show("Database has been created successfully!", "Create Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Create Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
tmpConn.Close();
}
return;
}
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
textBox3.Text = textBox1.Text + "_Data";
textBox10.Text = textBox1.Text + "_Log";
}
I am newbie to c# and I want to send a text file with a header and footer using a sql query.
I have an sql results in datagridview and then saved as text file. but everytime i run this query, i should get an header and footer from the sql query. So I am thinking of creating 2 buttons for headers and footers and when i click these it gets the value from sql to datagridview and it copies to textfile and the same for footer just appending different text to the samefile. I want any suggestions can i do like that.
private void btnGetData_Click(object sender, EventArgs e)
{
this.btnGetData.Enabled = false;
Application.DoEvents();
string stringSql = " SELECT distinct " +
"'" + comboBox6.Text + "' as RecordType" +
" , left([CPC No] +' ',30) " +
" , space(1983) " +
",'" + comboBox6.Text + " 'as RecordType" +
, left(t.t_reference + ' ' ,24 ) as ClaimantReference " +
" , left([Claim Number] +' ',30) " +
" , " + comboBox4.Text + " as CourtCode" +
" ,left(ta_title +' ',30) as Title " +
" ,left(ta_surname +' ',30) as Surname " +
", space(180), bat.PCN_Charge as ClaimAmount " +
",[Court Fee] " +
",[Solictors Fees]" +
", (bat.PCN_Charge + [Court Fee]) as TotalAmount" +
",[POC1]" +
",'" + textBox2.Text + "' as RequestType" +
//",'" + comboBox1.Text + "' as RecordType" +
",'" + textBox3.Text + "' as TotalCourtFee" +
",'" + textBox4.Text + "' as TotalClaimAmount" +
" , space(1966) " +
" FROM tickets t " +
" LEFT OUTER JOIN " +
"( " +
" SELECT ticket_addresses.ta_system_ref, ta_title, ta_othername, ta_surname, ta_house_number, ta_address_1, ta_address_2, " +
" ta_address_3, ta_address_4, ta_post_code, ta_telephone, ta_organisation " +
" FROM ticket_addresses " +
" INNER JOIN " +
" ( " +
" SELECT ticket_addresses.ta_system_ref, MAX(ta_address_code) AS ta_address_code " +
" FROM ticket_addresses " +
" GROUP BY ta_system_ref " +
" ) ad " +
" ON (ticket_addresses.ta_system_ref=ad.ta_system_ref AND ticket_addresses.ta_address_code=ad.ta_address_code) " +
")ta " +
"ON (t.t_number=ta.ta_system_ref) " +
" " +
" Inner JOIN " +
" ticket_hold_record b " +
" ON ( t.t_number = b.thr_system_ref) " +
" " +
"Inner JOIN " +
"Rpt_PCNBalance_ALLTickets bat " +
"ON (t.t_number = bat.t_number) " +
" " +
"Inner JOIN " +
"hold_reasons ch " +
"ON (b.thr_hold_type = ch.hr_code) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[Courtfees] cf " +
" ON (bat.Payments >= cf. [Min ClaimAmount]) and (bat.Payments <= cf.[Max Claim Amount]) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[sites] s " +
" ON (t.t_contract = s.Contract) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[claim info] cc " +
" ON (cc.Code COLLATE DATABASE_DEFAULT = t.t_offence_code COLLATE DATABASE_DEFAULT) " +
" and t.t_reference IN {where} ";
//Generate list of Ticket IDS for SQL Where Clause
string whereClause = "";
string[] tempArray = new string[this.txt.Lines.Length];
tempArray = this.txt.Lines;
if (this.txt.Lines.Length == 0)
{
return;
}
for (int counter = 0; counter <= tempArray.Length-1; counter++)
{
if (tempArray[counter].Trim().Length > 0)
{
whereClause = whereClause + "'" + tempArray[counter] + "'" + ", ";
}
}
whereClause = whereClause.TrimEnd(' ', ',');
whereClause = "(" + whereClause + ")";
stringSql = stringSql.Replace("{where}", whereClause);
myDataset = new DataSet("SQL");
SqlConnection myConn = new SqlConnection();
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = stringSql;
myCommand.Connection = myConn;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myDataset);
this.dataGridView1.DataSource = myDataset.Tables[0];
for (int counter = 0; counter < myDataset.Tables[0].Columns.Count; counter++)
{
this.dataGridView1.Columns[counter].SortMode = DataGridViewColumnSortMode.NotSortable;
}
this.dataGridView1.Refresh();
myConn.Close(); this.btnGetData.Enabled = true;
this.btnSave.Enabled = true;
Application.DoEvents();
}
I'm developing some tool for a client, and they don't want to use LINQ to SQL, they also don't want to use WPF but I'm using it, they are afraid to new coding or something... But i can't with database, because they don't know anything about LINQ... so they gave me this annoying class (http://pastebin.com/VUzvN44i too long for paste here, sorry) which is "ok" when retrieving row by row...
But I have the following function, which is fully functional with linq to sql, but I'm lost with this class they gave me... So if someone can give me some advice on how to do it without modify the class it will be very helpful. Thanks.
private void GenerarFichero_Click(object sender, RoutedEventArgs e)
{
string valEmisora = "02827003";
string codigoCabecera;
if (DateTime.Today.Day > 7)
codigoCabecera = "AE570200";
else
codigoCabecera = "AE570100";
DataBaseDataContext dc = new DataBaseDataContext();
using (StreamWriter sw = new StreamWriter(codigoCabecera.Remove(6, 2)))
{
sw.WriteLine("775701 " + DateTime.Now.ToString("yy") + DateTime.Now.Month.ToString("d2") + DateTime.Now.AddDays(1).Day.ToString("d2") + DateTime.Now.Hour.ToString("d2") + DateTime.Now.Minute.ToString("d2") + "008910 00" + txtBanco.Text + codigoCabecera + txtBanco.Text + "");
sw.WriteLine("0170 " + valEmisora + " " + this.txtBanco.Text + " 10" + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy"));
var OutputQuery =
from o in dc.Seguros
group o by o.emisora;
List<int> TotalRegistros = new List<int>();
List<int> TotalSumas = new List<int>();
foreach (var grupo in OutputQuery)
{
sw.WriteLine("0270 " + valEmisora + grupo.Key + " " + this.txtBanco.Text + " 10" + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy"));
List<int> Suma = new List<int>();
foreach (var data in grupo)
{
Suma.Add(Convert.ToInt32(data.importe + data.importe_dec));
sw.WriteLine("6070 " + valEmisora + data.emisora + "1" + data.banco + data.sucursal + data.fecha + data.importe + data.importe_dec + data.identificacion + " " + data.referencia);
}
TotalRegistros.Add((grupo.Count() + 2));
TotalSumas.Add(Suma.Sum());
sw.WriteLine("8070 " + valEmisora + grupo.Key + " " + (grupo.Count() + 2).ToString().PadLeft(6, '0') + " " + Suma.Sum().ToString().PadLeft(12, '0'));
}
sw.WriteLine("9070 " + valEmisora + " " + (TotalRegistros.Sum() + 2).ToString().PadLeft(6, '0') + " " + TotalSumas.Sum().ToString().PadLeft(12, '0'));
this.txtTotal.Text = TotalSumas.Sum().ToString();
}
MessageBox.Show("El fichero ha sido guardado, ya no se puede editar");
}
I am not proud of what I'll be saying but since you desperately need a solution here it goes...
The quick and dirty way to work with this is:
var connection = InitalizeConnectionToDb();
var select = new SelectBD();
// Get the data from database
select.Open(connection, #"select * from Seguros");
// Simulate the grouping
var dictionary = new Dictionary<string, List<DataRow>>();
foreach(var row in select.DataTable)
{
var key = Convert.ToString(row["emisora"]);
if(!dictionary.ContainsKey(key))
{
dictionary[key] = new List<DataRow>();
}
dictionary[key].Add(row);
}
Now you can use the dictionary above to perform your calculations because the data is grouped by emisora field.
Well, I have the final code working, I've replaced OutputQuery with DataTable.AsEnumerable and actually it is working... This is what the code looks now
private void GenerarFichero_Click(object sender, RoutedEventArgs e)
{
string valEmisora = "02827003";
string codigoCabecera;
if (DateTime.Today.Day > 7)
codigoCabecera = "AE570200";
else
codigoCabecera = "AE570100";
using (StreamWriter sw = new StreamWriter(codigoCabecera.Remove(6, 2)))
{
sw.WriteLine("775701 " + DateTime.Now.ToString("yy") + DateTime.Now.Month.ToString("d2") + DateTime.Now.AddDays(1).Day.ToString("d2") + DateTime.Now.Hour.ToString("d2") + DateTime.Now.Minute.ToString("d2") + "008910 00" + txtBanco.Text + codigoCabecera + txtBanco.Text + "");
sw.WriteLine("0170 " + valEmisora + " " + this.txtBanco.Text + " 10" + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy"));
SelectBD sel = new SelectBD(App.ConexBD, "SELECT * FROM Seguros");
var Query = sel.DataTable.AsEnumerable().Select(row =>
{
return new
{
banco = row["banco"].ToString(),
emisora = row["emisora"].ToString(),
sucursal = row["sucursal"].ToString(),
fecha = row["fecha"].ToString(),
identificacion = row["identificacion"].ToString(),
importe = row["importe"].ToString(),
importe_dec = row["importe_dec"].ToString(),
provincia = row["provincia"].ToString(),
referencia = row["referencia"].ToString(),
};
});
var OutputQuery = Query.GroupBy(l => l.emisora);
List<int> TotalRegistros = new List<int>();
List<int> TotalSumas = new List<int>();
foreach (var grupo in OutputQuery)
{
sw.WriteLine("0270 " + valEmisora + grupo.Key + " " + this.txtBanco.Text + " 10" + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy"));
List<int> Suma = new List<int>();
foreach (var data in grupo)
{
Suma.Add(Convert.ToInt32(data.importe + data.importe_dec));
sw.WriteLine("6070 " + valEmisora + data.emisora + "1" + data.banco + data.sucursal + data.fecha + data.importe + data.importe_dec + data.identificacion + " " + data.referencia);
}
TotalRegistros.Add((grupo.Count() + 2));
TotalSumas.Add(Suma.Sum());
sw.WriteLine("8070 " + valEmisora + grupo.Key + " " + (grupo.Count() + 2).ToString().PadLeft(6, '0') + " " + Suma.Sum().ToString().PadLeft(12, '0'));
}
sw.WriteLine("9070 " + valEmisora + " " + (TotalRegistros.Sum() + 2).ToString().PadLeft(6, '0') + " " + TotalSumas.Sum().ToString().PadLeft(12, '0'));
this.txtTotal.Text = TotalSumas.Sum().ToString();
}
MessageBox.Show("El fichero ha sido guardado, ya no se puede editar");
}
I want to ask why query return null and not update what i want. Sorry I'm still new with asp.net and c#
myquery = "UPDATE kenderaan SET buatan = " + "'" + carmake + "'" + "," +
"model = " + "'" + carmodel + "'" + "," +
"no_enjin = " + "'" + carenjin + "'" + "," +
"cc = " + carcc + "," +
"seatCapacity = " + carseat + "," +
"tahunBuatan = " + caryear + " WHERE no_kenderaan = " + "'" + carid + "'" + "," +
"AND ic = " + "'" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
restructure your code into this, use Connection object, Command Object, using statement.
string myquery = "UPDATE kenderaan SET buatan = #carmake ," +
" model = #carmodel ," +
" no_enjin = #carenjin ," +
" cc = #carcc ," +
" seatCapacity = #carseat ," +
" tahunBuatan = #caryear " +
"WHERE no_kenderaan = #carid " +
" AND ic = #cusid ";
using (MySqlConnection _conn = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand _comm = new MySqlCommand())
{
_comm.Connection = _conn;
_comm.CommandText = myquery;
_comm.CommandType = CommandType.Text;
_comm.Parameters.AddWithValue("#carmake",carmake);
_comm.Parameters.AddWithValue("#carmodel",carmodel);
_comm.Parameters.AddWithValue("#carenjin",carenjin);
_comm.Parameters.AddWithValue("#carcc",carcc);
_comm.Parameters.AddWithValue("#carseat",carseat);
_comm.Parameters.AddWithValue("#caryear",caryear);
_comm.Parameters.AddWithValue("#carid",carid);
_comm.Parameters.AddWithValue("#cusid",cusid);
try
{
_conn.Open();
_comm.ExecuteNonQuery();
MessageBox.Show("Updated!");
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString()); // as mentioned on the comment
}
}
}
Reasons why you need to parameterized your query:
avoids SQL Injection
makes your code more readable
etc.. :D
Sources
AddWithValue
Add (recommended and leaving you this as an assignment :D)
Create a DbCommand to execute the Update statement by using ExecuteNonQuery() method. If you are using SQL Server then you can use this piece of code snippet:
using System.Data.SqlClient;
string query = "UPDATE kenderaan SET buatan = #carmake" +
", model = #carmodel" +
", no_enjin = #carenjin" +
", cc = #carcc" +
", seatCapacity = #carseat" +
", tahunBuatan = #caryear" +
" WHERE no_kenderaan = #carid AND ic = #cusid";
using (SqlConnection conn = new SqlConnection("<connection string>"))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#carmake", carmake);
cmd.Parameters.AddWithValue("#carmodel", carmodel);
cmd.Parameters.AddWithValue("#carenjin", carenjin);
cmd.Parameters.AddWithValue("#carcc", carcc);
cmd.Parameters.AddWithValue("#carseat", carseat);
cmd.Parameters.AddWithValue("#caryear", caryear);
cmd.Parameters.AddWithValue("#carid", carid);
cmd.Parameters.AddWithValue("#cusid", cusid);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try this code in place of your code:
and make sure that varchar parameters are compare to string values.
string myquery = "UPDATE kenderaan SET buatan = '" + carmake + "',model = '"+
carmodel + "',no_enjin = '" +carenjin + "',cc = " + carcc + ",seatCapacity = " +
carseat + ",tahunBuatan = " + caryear +
" WHERE no_kenderaan = '" + carid + "' AND ic = '" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
UPDATED: Apologize, I had just corrected your query with your where condition I just removed comma which you used to separate two condition.
To avoid SQL Injection Attacks, Use one of these :
1) Parameters with Stored Procedures
2) Use Parameters with Dynamic SQL
3) Constrain Input
you can find more information over HERE