i am getting error on sda.Fill(dt); that Fill:selectcommand.connction property has not been initialised what could be a problem in connection?
protected void Updatecustomer(object sender, GridViewUpdateEventArgs e)
{
string cstid = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblcustomerid")).Text;
string csnm = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname")).Text;
string cmpn = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtcompany")).Text;
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\LENOVO\\Documents\\Visual Studio 2010\\WebSites\\LiveSms\\App_Data\\Sms.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update gridCompany set name=#name,company=#company where cid=#cid;
cmd.Parameters.Add("#cid", SqlDbType.NVarChar).Value = cstid;
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = csnm;
cmd.Parameters.Add("#comnpany", SqlDbType.NVarChar).Value = cmpn;
GridView1.EditIndex = -1;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
Related
I'm trying to use SSIS to import multiple files from a folder, and i dont know the SheetName.
So, I'm creating a script task according to below link, to get SheetName, but i got error in the script task 'array size cannot be specified in a variable declaration'
http://www.anupamanatarajan.com/2011/01/dynamic-sheet-name-in-ssis-excel.html
public void Main()
{
// TODO: Add your code here
string excelFile = null;
string connectionString = null;
OleDbConnection excelConnection = null;
DataTable tablesInFile = null;
int tableCount = 0;
DataRow tableInFile = null;
string currentTable = null;
int tableIndex = 0;
string[] excelTables = null;
excelFile = Dts.Variables["User::BBGFilePath"].Value.ToString();
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";Extended Properties=Excel 8.0";
excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
tablesInFile = excelConnection.GetSchema("Tables");
tableCount = tablesInFile.Rows.Count;
excelTables = new string[tableCount];
foreach (DataRow tableInFile_loopVariable in tablesInFile.Rows)
{
tableInFile = tableInFile_loopVariable;
currentTable = tableInFile["TABLE_NAME"].ToString();
excelTables[tableIndex] = currentTable;
tableIndex += 1;
}
}
//Provide value to the shetename variable
Dts.Variables["User::SheetName"].Value = excelTables[0];
//Display file name
string strMessage = Dts.Variables["User::BBGFilePath"].Value.ToString();
MessageBox.Show(strMessage);
Dts.TaskResult = (int)ScriptResults.Success;
}
So i tried to add the [User:SheetName] variable to the Script task, but it doesn't work.
can anyone please check what is missing?
As I had mentioned earlier, the error does clearly suggested you have some non-declaration statements at the class level which is not valid.
Your code from the script task have some issues with the closing brace --
public void Main()
{
// TODO: Add your code here
string excelFile = null;
string connectionString = null;
OleDbConnection excelConnection = null;
DataTable tablesInFile = null;
int tableCount = 0;
DataRow tableInFile = null;
string currentTable = null;
int tableIndex = 0;
string[] excelTables = null;
excelFile = Dts.Variables["User::BBGFilePath"].Value.ToString();
//Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\CESLtd\ELKAY\Reports\Work2\Book1.xls; Extended Properties = "EXCEL 8.0;HDR=YES";
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";Extended Properties=Excel 8.0;HDR=YES";
excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
tablesInFile = excelConnection.GetSchema("Tables");
tableCount = tablesInFile.Rows.Count;
excelTables = new string[tableCount];
foreach (DataRow tableInFile_loopVariable in tablesInFile.Rows)
{
tableInFile = tableInFile_loopVariable;
currentTable = tableInFile["TABLE_NAME"].ToString();
excelTables[tableIndex] = currentTable;
tableIndex += 1;
}
//} **commented this line now you are good to go**
//Provide value to the shetename variable
Dts.Variables["User::SheetName"].Value = excelTables[0];
//Display file name
string strMessage = Dts.Variables["User::BBGFilePath"].Value.ToString();
MessageBox.Show(strMessage);
Dts.TaskResult = (int)ScriptResults.Success;
}
I am new to SharePoint programming.
Can anyone tell me how I can export list data to Excel using a timer job with some custom code?
Please go through the below link for creating timer jobs in sharepoint.
This article is contain the detailed process.
https://www.mssqltips.com/sqlservertip/3801/custom-sharepoint-timer-job/
The below code will help you to export the list data.
public void Export(List<int> ids)
{
DataTable table = new DataTable();
try
{
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteE = new SPSite(site.ID))
{
using (SPWeb webE = siteE.OpenWeb(web.ID))
{
webE.AllowUnsafeUpdates = true;
SPList list = webE.Lists["Stationery"];
table.Columns.Add("Product", typeof(string));
table.Columns.Add("Quantity", typeof(Decimal));
DataRow newRow;
GridView gv = new GridView();
foreach (SPListItem item in list.Items)
{
if (ids.Contains(Convert.ToInt32(item["ID"].ToString())) && (item["Status"].ToString() == "New"))
{
newRow = table.Rows.Add();
newRow["Product"] = item["Product"].ToString();
newRow["Quantity"] = Convert.ToDecimal(item["Quantity"].ToString());
item["Status"] = "Exported";
item.Update();
}
}
SPBoundField boundField = new SPBoundField();
boundField.HeaderText = "Product";
boundField.DataField = "Product";
gv.Columns.Add(boundField);
boundField = new SPBoundField();
boundField.HeaderText = "Quantity";
boundField.DataField = "Quantity";
boundField.ControlStyle.Width = new Unit(120);
gv.Columns.Add(boundField);
gv.AutoGenerateColumns = false;
gv.DataSource = table.DefaultView;
gv.DataBind();
gv.AllowSorting = false;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
string attachment = "attachment; filename=export" + "_" + DateTime.Now.ToShortTimeString() + ".xls";
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/Excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
HttpContext.Current.Response.End();
webE.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HttpContext.Current.Response.Write(ex.ToString());
}
I want my checkbox to be visible as button. Check-boxes are generated dynamically in code behind file using C#.
How can I do that?
private void loadItems()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "ConString";
con.Open();
SqlCommand cmd = new SqlCommand("Select ItemId,ItemName from ITEMS", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
iid = (dt.Rows[i]["ItemId"]).ToString();
iname = dt.Rows[i]["ItemName"].ToString();
CheckBox btn = new CheckBox();
btn.Content = iname;
btn.Height = 20;
btn.Width = 150;
btn.Tag = iname;
//var2 = btn.Tag.ToString();
wrapItems.Children.Add(btn);
btn.Click += new RoutedEventHandler(CheckBoxChecked);
//btn.RaiseEvent(new RoutedEventArgs(Button.btnClick(sender,e)));
con.Close();
}
I want to send DataSet data with email excel file attachment in C# but I don't want to create Excel file physically. It can be do with MemoryStream but I couldn't.
Another problem I want to set Excel file's encoding type because data may be Russian or Turkish special character.
Please help me...
Here is my sample code...
<!-- language: c# -->
var response = HttpContext.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.Default;
GridView excelGridView = new GridView();
excelGridView.DataSource = InfoDataSet;
excelGridView.DataBind();
excelStringWriter = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(excelStringWriter);
excelGridView.RenderControl(htw);
byte[] ExcelData = emailEncoding.GetBytes(excelStringWriter.ToString());
MemoryStream ms = new MemoryStream(ExcelData);
mailMessage.Attachments.Add(new Attachment(ms, excelFileName, "application/ms-excel"));
<!-- language: c# -->
here is another one simple and easy with excel attchment
public string SendMail(string LastId)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_GetMailData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#LastID", LastId);
con.Open();
string result = "0";
string temptext = "";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
//ExportToSpreadsheet(dt,"My sheet");
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
AttachandSend(gv);
con.Close();
return result.ToString();
}
public void AttachandSend(GridView gv)
{
StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
gv.RenderControl(hw);
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
MailAddress address = new
MailAddress("xxxxxxxxxxxxx", "Admin");
mailMessage.Attachments.Add(new Attachment(mAtt, "sales.xls"));
mailMessage.Body = "Hi PFA";
mailMessage.From = address;
mailMessage.To.Add("xxxxxxxxxxxx");
mailMessage.Subject = "xxxxxxxxxxxxxx";
mailMessage.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.Send(mailMessage);
}
Here is your solution
private static Stream DataTableToStream(DataTable table)
{
const string semiColon = ";";
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName);
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
}
return ms;
}
private static MailMessage CreateMail(string from,
string to,
string subject,
string body,
string attname,
Stream tableStream)
{
// using System.Net.Mail
var mailMsg = new MailMessage(from, to, subject, body);
tableStream.Position = 0;
mailMsg.Attachments.Add(
new Attachment(tableStream, attname, CsvContentType));
return mailMsg;
}
private const string CsvContentType = "application/ms-excel";
private static void ExportToSpreadsheetInternal(Stream tableStream, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = CsvContentType;
context.Response.AppendHeader(
"Content-Disposition"
, "attachment; filename=" + name + ".xls");
tableStream.Position = 0;
tableStream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
var stream = DataTableToStream(table);
var mailMsg = CreateMail("from#ddd.com",
"to#ddd.com",
"spread",
"the spread",
name,
stream);
//ExportToSpreadsheetInternal(stream, name);
// send the mailMsg with SmtpClient (config in your web.config)
var smtp = new SmtpClient();
smtp.Send(mailMsg);
}
Call this method
ExportToSpreadsheet(DataTable table, string name)
I am exporting data from sql server database to excel in wpf, and I have achieved the function successully. Now I want to change the head column colour in the generated excel. Any ideas? Thanks in advance.
private void button1_Click(object sender, RoutedEventArgs e)
{
string sql = null;
string data = null;
// string path = null;
//string myfilename = "Report";
int i = 0;
int j = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
//xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Name = "Customer List";
//connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
//SqlConnection cnn = new SqlConnection(GetConnectionString());
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = #"Data Source=.\sqlexpress;Initial Catalog=ClientLists;Integrated Security=SSPI;";
cnn.Open();
sql = "select FirstName, LastName, City, PostCode, TelephoneNo from Customers";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count -1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count -1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 2, j + 1] = data;
}
}
Microsoft.Office.Interop.Excel.Range headerRange1 = xlWorkSheet.get_Range("A1", "A1");
headerRange1.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange1.Value = "First Name";
headerRange1.Font.Bold = true;
headerRange1.ColumnWidth = 14;
// headerRange1.Interior.Color = 1;
// headerRange1.Borders.Color = System.Drawing.Color.Red;
Microsoft.Office.Interop.Excel.Range headerRange2 = xlWorkSheet.get_Range("B1", "B1");
headerRange2.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange2.Value = "Last Name";
headerRange2.Font.Bold = true;
headerRange2.ColumnWidth = 14;
Microsoft.Office.Interop.Excel.Range headerRange3 = xlWorkSheet.get_Range("C1", "C1");
headerRange3.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange3.Value = "City";
headerRange3.Font.Bold = true;
headerRange3.ColumnWidth = 14;
Microsoft.Office.Interop.Excel.Range headerRange4 = xlWorkSheet.get_Range("D1", "D1");
headerRange4.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange4.Value = "Post Code";
headerRange4.Font.Bold = true;
headerRange4.ColumnWidth = 14;
Microsoft.Office.Interop.Excel.Range headerRange5 = xlWorkSheet.get_Range("E1", "E1");
headerRange5.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange5.Value = "Telephone NO";
headerRange5.Font.Bold = true;
headerRange5.ColumnWidth = 14;
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
There is a post that can be found here that says that this is not possible.
However, the c# excel how to change a color of a particular row post on StackOverflow that provides code for changing a row colour... you may be able to adapt it for you purposes.