since I am beginner, Jtable concept has made my brain rack a lot. with difficult i have maganaged to read a database and add it to jtable CODE given below. but am stuck as how to ADD A JCHECKBOX IN THE LAST COLUMN OF THE SAME TABLE.
public class ttt extends JFrame{
ResultSet rs;
int colcount;
String[] headers;
Connection con;
Statement st;
ttt(){
final Vector columnNames = new Vector();
final Vector data = new Vector();
JPanel panel=new JPanel();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded");
// Establish a connection
con= DriverManager.getConnection
("jdbc:odbc:ysr");
System.out.println("Database connecteddddd");
// Create a statement
st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT
Block_Name,Panchayat_Name,Village_Name," +
" Habitation_Name,Scheme_Name,Sanction_Amount FROM
ysr2011 where Habitation_Name= '10th mile' ");
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
}
catch(Exception e){}
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
add(panel);
}
public static void main(String arg[])
{
try
{
ttt frame=new ttt();
frame.setSize(550,200);
frame.setVisible(true);
}
catch(Exception e)
{}
}
}
ANY HELP IS REALLY A WELCOME GESTURE. THANKING IN ADVANCE.
You would add the check box here:
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
columnNames.addElement("Check Box");
while (rs.next()) {
Vector row = new Vector(columns + 1);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
row.addElement(new JCheckBox());
data.addElement( row );
}
Use your own column title. You're also going to have to define the check boxes more completely because eventually you're going to add tests for the isSelected method.
Related
I am migrating a c# application from sql server express edition to postgresql using npgsql 4.1.3.1. However I am getting the syntax error 42601 whenever i try to add row a databound datagridview programmatically. I had a look at the update command generated by npgsqlcommandbuilder and it includes an extra parenthesis at the end. ("pfuppersalarylimit" = #p133)) of the command. Any help shall be highly appreciated.
`NpgsqlConnection con;`
NpgsqlCommand sqlcmd;
NpgsqlCommandBuilder builder;
DataSet ds;
BindingSource bs = new BindingSource();
public frmEmployee()
{
string str = Properties.Settings.Default.connectionstring; //.Settings.connectionstring2;
con = new Npgsql.NpgsqlConnection(str); //
InitializeComponent();
}
private void frmEmployee_Load(object sender, EventArgs e)
{
string sql = "Select * from employee where company_code='S00159' order by rownumber";
ds = new DataSet();
da = new NpgsqlDataAdapter(sql, con);
builder = new NpgsqlCommandBuilder(da);
da.Fill(ds);
bs.DataSource = ds;
bs.DataMember = ds.Tables[0].ToString();
DataGridView1.DataSource = bs;
}
private void addemployee_Click(object sender, EventArgs e)
{
int start_row_number;
int pos1;
try
{
if (DataGridView1.Rows.Count == 0)
{
pos1 = 0;
start_row_number = 1; // added on 15/10/2011
}
else
{
pos1 = DataGridView1.CurrentCell.RowIndex + 1;
start_row_number = Convert.ToInt32(DataGridView1.Rows[pos1 - 1].Cells["rownumber"].Value) + 1;
}
DataRow employeeRow = ds.Tables[0].NewRow();
string emplcode = companyInfo.company_code.Substring(1, 1) + classMisc.genEmployeeCodeNew(); // just a random number
employeeRow["company_code"] = companyInfo.company_code.Trim();
employeeRow["employee_code_no"] = emplcode;
employeeRow["srno"] = classMisc.getsrno();
employeeRow["flag"] = true;
employeeRow["rownumber"] = start_row_number; // pos1
employeeRow["mobile"] = 0;
employeeRow["aadhar"] = 0;
employeeRow["pfuppersalarylimit"] = 0;
ds.Tables[0].Rows.InsertAt(employeeRow, pos1);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "error 1");
}
}
Hi i have a jtable in witch i want to save and load from a txtfile.
Now i have achived that but now im wondering in witch manner could i import the data into a already created arraylist.
Import Code
String filePath = "C:\\Users\\ellim\\Desktop\\TitanPanel\\TitanPanel.txt";
File file = new File(filePath);
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
DefaultTableModel model = (DefaultTableModel) tbl_panels.getModel();
Object[] lines = br.lines().toArray();
for (int i = 0; i < lines.length; i++) {
String[] row = lines[i].toString().split(" ");
model.addRow(row);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(PanelTable.class.getName()).log(Level.SEVERE, null, ex);
}
Export Code
String filePath = "C:\\Users\\ellim\\Desktop\\TitanPanel\\TitanPanel.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < tbl_panels.getRowCount(); i++) {
for (int j = 0; j < tbl_panels.getColumnCount(); j++) {
bw.write(tbl_panels.getValueAt(i, j).toString() + " ");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(PanelTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
Arraylist i want to save into
ArrayList documentos;
Here is code for ArrayList export
ArrayList<String> documentos = new ArrayList<String>();
// here i am using , as separator
ArrayListExporter exporter = new ArrayListExporter ( documentos , "," );
exporter.export( tbl_panels );
public interface TableDataExporter {
public void export( JTable table );
}
public class FileExporter implements TableDataExporter {
private String fileName;
private String separator ;
public FileExporter( String fileName,String separator ) {
this.fileName=fileName;
this.separator=separator;
}
public void export( JTable table ) {
File file = new File(fileName);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < tbl_panels.getRowCount(); i++) {
for (int j = 0; j < tbl_panels.getColumnCount(); j++) {
if( j != 0 ) {
bw.write( separator );
}
bw.write(tbl_panels.getValueAt(i, j).toString() );
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(PanelTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class ArrayListExporter implements TableDataExporter {
private List<String> list;
private String separator;
public FileExporter( List<String> list,String separator ) {
this.list=list;
this.separator=separator;
}
public void export( JTable table ) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < tbl_panels.getRowCount(); i++) {
builder.delete(0,builder.length());
for (int j = 0; j < tbl_panels.getColumnCount(); j++) {
if( j != 0 ) {
builder.append( separator );
}
Object obj = tbl_panels.getValueAt(i, j);
builder.append( obj == null ? "null" : obj.toString() );
}
}
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm using C# to rewrite some ColdFusion code.
The CF code looks like this:
An array contains a struct that consists of two sections:
Another struct, which contains header data extracted from a data file.
A 2D array that contains the actual data from each row in the same data file.
In C#, I'm using Dictionary and Jagged Array. See the code below. Are these the best data structures to use?
// Create AllDataArray that contains HeaderAndDataDict.
Dictionary<string, object>[] AllDataArray = new Dictionary<string, object>[1];
// Create HeaderAndData Dictionary.
Dictionary<string, object> HeaderAndDataDict = new Dictionary<string, object>();
// Add HeaderAndDataDict to AllDataArray[0].
AllDataArray[0] = HeaderAndDataDict;
// Create Header Dictionary.
Dictionary<string, string> HeaderDict = new Dictionary<string, string>();
// Populate Header Dictionary
HeaderDict.Add("Create Date", "10/20/2014");
HeaderDict.Add("ABC Rank", "ALL");
HeaderDict.Add("Status", "All");
// Add Header Dictionary to HeaderAndDataDict.
HeaderAndDataDict.Add("Header", HeaderDict);
// Create jagged array.
string[][] DataJaggedArray = new string[2][];
DataJaggedArray[0] = new string[] { "aaaa0", "bbbb0", "cccc0" };
DataJaggedArray[1] = new string[] { "aaaa1", "bbbb1", "cccc1" };
// Add DataJaggedArray to HeaderAndDataDict.
HeaderAndDataDict.Add("Data", DataJaggedArray);
// Display data.
for (int a = 0; a < AllDataArray.Length; a++)
{
Console.WriteLine("AllDataArray = " + a);
foreach (var key1 in HeaderAndDataDict.Keys)
{
Console.WriteLine("key= " + key1);
if (key1.Equals("Header"))
{
var valueHeader = (Dictionary<string, string>)HeaderAndDataDict[key1];
foreach (var key2 in valueHeader.Keys)
{
Console.WriteLine("valueHeader= {0}= {1}", key2, valueHeader[key2]);
}
}
else if (key1.Equals("Data"))
{
var valueData = (string[][])HeaderAndDataDict[key1];
Console.WriteLine("valueData length= " + valueData.Length);
for (int i = 0; i < valueData.Length; i++)
{
for (int j = 0; j < valueData[i].Length; j++)
{
Console.WriteLine("valueData= i= " + i + " j= " + j + " " + valueData[i][j]);
}
}
}
}
} // AllDataArray for loop
Consider using an object-oriented approach to hold your data. This means creating a class that holds the headers and data rows:
public class DataItem
{
private readonly Dictionary<string, string> _headers = new Dictionary<string, string>();
private readonly List<string[]> _rows = new List<string[]>();
public IEnumerable<string> Headers
{
get { return _headers.Keys; }
}
public void AddHeader(string key, string value)
{
_headers.Add(key, value);
}
public string GetHeader(string key)
{
return _headers[key];
}
public string[] GetDataRow(int rowNumber)
{
return _rows[rowNumber];
}
public void AddDataRow(string[] row)
{
_rows.Add(row);
}
public int RowCount
{
get { return _rows.Count; }
}
}
When you have this infrastructure ready, the actual implementation becomes simpler and less error-prone:
//add data
List<DataItem> allData = new List<DataItem>();
var dataItem = new DataItem();
dataItem.AddHeader("Create Date", "10/20/2014");
dataItem.AddHeader("ABC Rank", "ALL");
dataItem.AddHeader("Status", "All");
dataItem.AddDataRow(new [] {"aaaa0", "bbbb0", "cccc0"});
dataItem.AddDataRow(new[] {"aaaa1", "bbbb1", "cccc1"});
allData.Add(dataItem);
//display data
foreach (var item in allData)
{
Console.WriteLine("New item:");
foreach (var header in item.Headers)
{
Console.WriteLine("{0}: {1}", header, item.GetHeader(header));
}
for (int i = 0; i < item.RowCount; i++)
{
var row = item.GetDataRow(i);
for (int j = 0; j < row.Length; j++)
{
Console.WriteLine("Cell ({0}, {1}): {2}", i, j, row[j]);
}
}
}
Additionaly, if you like to, you could move the printing code to within the data item class:
public class DataItem
{
public void Print()
{
Console.WriteLine("New item:");
foreach (var header in Headers)
{
Console.WriteLine("{0}: {1}", header, GetHeader(header));
}
for (int i = 0; i < RowCount; i++)
{
var row = GetDataRow(i);
for (int j = 0; j < row.Length; j++)
{
Console.WriteLine("Cell ({0}, {1}): {2}", i, j, row[j]);
}
}
}
}
Then using it like this:
//display data
foreach (var item in allData)
{
item.Print();
}
This will have the advantage that if you require printing from somewhere else in your program you can do it more easily. This can also work for other things like loading data from a text file, or saving it back.
Update
To access your data using LINQ, here is an example that filters on rows and headers, then sorts the results by the value in the Create Date header.
var query = from item in allData
where item.GetHeader("Status") == "Status 1"
&& item.GetHeader("ABC Rank") == "3"
&& item.GetDataRow(1).Contains("bbbb1")
orderby item.GetHeader("Create Date")
select item;
foreach (var item in query)
item.Print();
They are valid choices.
I don't think there is a "best" solution for all usages
It depends on how you plan to access them (number of read / write operations, thread safety, ...).
I am new to TestNG framework. Please guide how to parameterise the test cases using Apache POI(Excel).
I have a code to read from second row from Excel.
public class spreadData {
private transient Collection data = null;
public spreadData(final InputStream excelInputStream) throws IOException {
this.data = loadFromSpreadsheet(excelInputStream);
}
public Collection getData() {
return data;
}
private Collection loadFromSpreadsheet(final InputStream excelFile)
throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(excelFile);
data = new ArrayList();
Sheet sheet = workbook.getSheetAt(0);
int numberOfColumns = countNonEmptyColumns(sheet);
List rows = new ArrayList();
List rowData = new ArrayList();
/*for (Row row : sheet) {
if (isEmpty(row)) {
break;
} else {
rowData.clear();
for (int column = 0; column < numberOfColumns; column++) {
Cell cell = row.getCell(column);
rowData.add(objectFrom(workbook, cell));
}
rows.add(rowData.toArray());
}
}*/
int rowStart = 1;
//int rowEnd = Math.max(1400, sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum <= sheet.getLastRowNum(); rowNum++) {
//Row r = sheet.getRow(rowNum);
Row read = sheet.getRow(rowNum);
if (isEmpty(read)) {
break;
} else {
rowData.clear();
for (int column = 0; column < numberOfColumns; column++) {
Cell cell = read.getCell(column);
rowData.add(objectFrom(workbook, cell));
}
rows.add(rowData.toArray());
}
}
return rows;
}
private boolean isEmpty(final Row row) {
Cell firstCell = row.getCell(0);
boolean rowIsEmpty = (firstCell == null)
|| (firstCell.getCellType() == Cell.CELL_TYPE_BLANK);
return rowIsEmpty;
}
/**
* Count the number of columns, using the number of non-empty cells in the
* first row.
*/
private int countNonEmptyColumns(final Sheet sheet) {
Row firstRow = sheet.getRow(0);
return firstEmptyCellPosition(firstRow);
}
private int firstEmptyCellPosition(final Row cells) {
int columnCount = 0;
for (Cell cell : cells) {
if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
break;
}
columnCount++;
}
return columnCount;
}
private Object objectFrom(final HSSFWorkbook workbook, final Cell cell) {
Object cellValue = null;
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
cellValue = cell.getRichStringCellValue().getString();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cellValue = getNumericCellValue(cell);
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cellValue = cell.getBooleanCellValue();
} else if (cell.getCellType() ==Cell.CELL_TYPE_FORMULA) {
cellValue = evaluateCellFormula(workbook, cell);
}
return cellValue;
}
private Object getNumericCellValue(final Cell cell) {
Object cellValue;
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = new Date(cell.getDateCellValue().getTime());
} else {
cellValue = cell.getNumericCellValue();
}
return cellValue;
}
private Object evaluateCellFormula(final HSSFWorkbook workbook, final Cell cell) {
FormulaEvaluator evaluator = workbook.getCreationHelper()
.createFormulaEvaluator();
CellValue cellValue = evaluator.evaluate(cell);
Object result = null;
if (cellValue.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
result = cellValue.getBooleanValue();
} else if (cellValue.getCellType() == Cell.CELL_TYPE_NUMERIC) {
result = cellValue.getNumberValue();
} else if (cellValue.getCellType() == Cell.CELL_TYPE_STRING) {
result = cellValue.getStringValue();
}
return result;
}
}
My question is how to parameterise the test cases using TestNG? means by using #DataProvider TestNG annotation.
Kindly help me with a sample code or explanation.
I'm not sure which set of data you want...but here's how a dataProvider works:
Say I have a test that takes a String and then an int like this:
#Test(dataProvider = "excelData")
public void executeTest(String name, int value){}
My data provider would look something like this:
#DataProvider(name = "excelData")
public Object[][] data(){
return new Object[][]{
{"Test",1},
{"More Testing",7},
{"Last Test",-5}}
}
The test will be run 3 times, with each row of the array is the set of data that is to be passed in. You will need to convert your excel data into such a format.
Note, you can also return an Iterator<Object[]> if you prefer.
I am following a tutorial "Export data from sql server database to excel in wpf". Now I can achieve the function successfully. But in the exported Excel file, there is no column names (database column headers like CustomerId, CustomerName, city, postcode, telephoneNo...)
.
How can I get this feature? Also, how can I open a SaveAs dialogue? Thanks. The following is my code:
private void button1_Click(object sender, RoutedEventArgs e)
{
string sql = null;
string data = null;
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.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = #"Data Source=.\sqlexpress;Initial Catalog=Client;Integrated Security=SSPI;";
cnn.Open();
sql = "select * 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 + 1, j + 1] = data;
}
}
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();
}
}
I'm not an expert in this, but I believe that you can use an underscore character (_) in a Range object to select or edit a column header:
xlWorkSheet.Range["A1", _].Value2 = "Heading for first column";