0% found this document useful (0 votes)
175 views7 pages

Data Grid

This document contains the code for a C# Windows Forms application that performs the following functions: 1. Loads data from an Excel spreadsheet into a DataSet and displays it in a datagrid. 2. Allows uploading selected data rows to a SQL database table via a stored procedure. 3. Generates a PDF report from the DataSet and opens it.

Uploaded by

bsgindia82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
175 views7 pages

Data Grid

This document contains the code for a C# Windows Forms application that performs the following functions: 1. Loads data from an Excel spreadsheet into a DataSet and displays it in a datagrid. 2. Allows uploading selected data rows to a SQL database table via a stored procedure. 3. Generates a PDF report from the DataSet and opens it.

Uploaded by

bsgindia82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

using

using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Data.Sql;
System.Data.OleDb;
System.Data.Common;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.Net.Http;
System.Net.Http.Headers;
System.Threading.Tasks;
System.Text.RegularExpressions;
Microsoft.Practices.EnterpriseLibrary.Common;
Microsoft.Practices.EnterpriseLibrary.Data;
Microsoft.Practices.EnterpriseLibrary.Data.Sql;
Microsoft.Practices.EnterpriseLibrary.Logging;

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
namespace BSG_SMS
{
public partial class Form1 : Form
{
DataSet ds;
OleDbConnection con;
OleDbCommand oledbCmd;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
test();
LoadSheet();
}
private void button1_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
string msg = textBox1.Text.Trim();
string url = "http://login.smsgatewayhub.com/smsapi/pushsms.aspx?
user=bsganesh82&pwd=898457&to=919840817231&sid=WEBSMS&msg=";
url += msg + "&fl=0 ";
try
{
HttpResponseMessage response = client.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else

Console.WriteLine("Failed");
}
// string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
string responseBody = client.GetStringAsync(url).Result;
Console.WriteLine(responseBody);

}
catch (HttpRequestException ee)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", ee.Message);
}

// Need to call dispose on the HttpClient object


// when done using it, so the app doesn't leak resources
// client.Dispose(true);

public void LoadSheet()


{
try
{
DataTable dt;
string path = System.IO.Path.GetFullPath("E:\\BSG\\test.xlsx");
//string excelFile = "@E:\\BSG\\test.xlsx";
//OleDbConnection con = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";" +
//
"Extended Properties='Excel 8.0;HDR={1}'");
con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + path + ";" +
"Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
cmbTables.DataSource = dt.DefaultView;
cmbTables.DisplayMember = "TABLE_NAME";

}
catch (Exception e)
{
}

public void test()


{
try
{

Database db = new
SqlDatabase("server=192.168.0.4;database=Fansplay;user=sa;password=Sql@chennai");
DbCommand cmd = db.GetStoredProcCommand("Get_Ff_Team");
ds = db.ExecuteDataSet(cmd);
Console.WriteLine(ds.Tables.Count);
DataRow dr = ds.Tables[0].Rows[0];
textBox1.Text = dr[1].ToString();
comboBox1.DataSource = ds.Tables[0].DefaultView;
comboBox1.DisplayMember = ds.Tables[0].Columns[2].ColumnName;
//comboBox1.SelectedIndex = -1;
textBox1.Text = (comboBox1.SelectedIndex).ToString();
GeneratePdf();
}
catch (Exception e)
{
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRow dr = ds.Tables[0].Rows[comboBox1.SelectedIndex];
// textBox1.Text = dr[0].ToString() + "-" + dr[1].ToString();
// textBox1.Text = (comboBox1.SelectedIndex).ToString();
}
private void button2_Click(object sender, EventArgs e)
{
string s="";
foreach (DataGridViewRow dgRow in dataGridView1.Rows)
{
int id = Convert.ToInt32(dgRow.Cells[1].Value);
s = s + id;
}
MessageBox.Show(s);
string mail = textBox1.Text;
try
{
Regex re = new Regex("^9[0-9]{9}");
//string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
// @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
// @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
string strRegex = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\
{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}
[a-z0-9]))$";
//Regex re = new Regex(strRegex);
if (re.IsMatch(mail))
MessageBox.Show("Valid");
else
MessageBox.Show("In Valid");
}
catch (Exception ee)
{
MessageBox.Show("In Valid");
}
}

private void textBox1_KeyDown(object sender, KeyEventArgs e)


{
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
e.Handled = true;
if ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
e.KeyCode == Keys.Decimal)
{
e.Handled = false;
}
//Code to only accept numerical buttons
base.OnKeyUp(e);
}
private void cmbTables_SelectedIndexChanged(object sender, EventArgs e)
{
//string tbl = cmbTables.SelectedItem.ToString();
DataView dv = (DataView)cmbTables.DataSource;
DataRow dr = dv.Table.Rows[cmbTables.SelectedIndex];
string tbl = dr["TABLE_NAME"].ToString();
try
{
if (tbl != "")
{
oledbCmd = new OleDbCommand();
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
oledbCmd.Connection = con;
oledbCmd.CommandType = CommandType.Text;
oledbCmd.CommandText = "SELECT * FROM [" + tbl + "]";
oleda = new OleDbDataAdapter(oledbCmd);
oleda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;

}
}
catch (Exception ee)
{}

void UploadData()
{
try {
OleDbDataReader oledbDr = oledbCmd.ExecuteReader();
while (oledbDr.Read())
{
UploadData(oledbDr);
}
}
catch (Exception e) {
}

}
void GeneratePdf()
{
DataTable DTable = ds.Tables[0];
FontFactory.RegisterDirectories();
iTextSharp.text.Font myfont = FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 12,
iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
pdfDoc.Open();
PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(@"E:\\Team.pdf",
FileMode.Create));
pdfDoc.Open();
PdfPTable _mytable = new PdfPTable(DTable.Columns.Count);
for (int j = 0; j < DTable.Columns.Count; ++j)
{
Phrase p = new Phrase(DTable.Columns[j].ColumnName, myfont);
PdfPCell cell = new PdfPCell(p);
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
_mytable.AddCell(cell);
}
//------------------------for (int i = 0; i < DTable.Rows.Count - 1; i++)
{
for (int j = 0; j < DTable.Columns.Count; j++)
{
Phrase p = new Phrase(DTable.Rows[i][j].ToString(), myfont);
PdfPCell cell = new PdfPCell(p);
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
_mytable.AddCell(cell);

}
}
//-----------------------pdfDoc.Add(_mytable);
pdfDoc.Close();
System.Diagnostics.Process.Start(@"E:\\Team.pdf");

}
int UploadData(OleDbDataReader oledbDr)
{

string sException = string.Empty;


int iTeamId = 0;
Database db;
try
{
db = new
SqlDatabase("server=192.168.0.4;database=Fansplay;user=sa;password=Sql@chennai");
DbCommand cmd = db.GetStoredProcCommand("Add_FF_Team");
db.AddOutParameter(cmd, "@id", DbType.Int32, 0);
db.AddInParameter(cmd, "@name", DbType.String, oledbDr[0]);
db.AddInParameter(cmd, "@code", DbType.String, oledbDr[1]);
db.AddInParameter(cmd, "@logo_URL", DbType.String, oledbDr[2]);
db.AddInParameter(cmd, "@created_by", DbType.Int16, oledbDr[4]);
db.AddInParameter(cmd, "@status", DbType.String, oledbDr[3]);
iTeamId = db.ExecuteNonQuery(cmd);

if (iTeamId != 0)
{
iTeamId = Convert.ToInt32(db.GetParameterValue(cmd, "@id"));
}
}
catch (Exception ex)
{
sException = "Team AddTeam | " + ex.ToString();
//Log.Write(ex.ToString(), 30101100, "DAL - Team - AddTeam ", 4);
// throw;
}
return iTeamId;
}
private void cmdUpload_Click(object sender, EventArgs e)
{
UploadData();
}
private void cmdExport_Click(object sender, EventArgs e)
{
// Bind table data to Stream Writer to export data to respective folder
System.IO.StreamWriter wr = new System.IO.StreamWriter(@"E:\\Team.xls");
// Write Columns to excel file
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Columns.Count; i++)
{
wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dt.Rows.Count); i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Rows[i][j] != null)
{
wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
wr.WriteLine();
}
wr.Close();
System.Diagnostics.Process.Start(@"E:\\Team.xls");
}
private void dataRepeater1_CurrentItemIndexChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{

}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
object value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (value is DBNull) { return; }
}
}

MessageBox.Show(value.ToString());

You might also like