How to Format DataGridView Cells after user input, also find average of Timespans

I'm a rather new to programming and slowly learning as best I can, and feel that I'm probably just getting hung up on some things because of my lack of overall understanding.  I've searched plenty online and these forums to figure out my issues, but
somethings just go over my head or I can't figure out how to make it work for what I'm trying to do.
On to what I'm trying to do.
I'm working on building an app for scoring swim meets for our conference.  I'm using a lcal SQL DB for all of the data and have a DGV on my form.  We don't have timing systems so we take 2 times from stop watches and then need to do an average
of the times to determine a swimmers time.  I have 3 fields for times, Time1, Time2 and AvgTime.
What I'm needing help with is how do I allow the user to not worry about formatting the time they enter but have it automatically format what they input after they exit the cell on Time1 and Time2.  Then I need to have it figure out the average of those
two times in AvgTime cell.  I'm able to get the averaging to work if I have the datatype set to decimal or int, but I can't get it to work if I have them set has TimeSpan.
Below is the code I have currently.  As you can see I've got things commented out that I found online but couldn't make work.
Thanks for taking the time to review this and help me out.
Public Class EventScoring
Private Sub EventScoring_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MeetDataSet.DualLineup' table. You can move, or remove it, as needed.
Me.DualLineupTableAdapter.Fill(Me.MeetDataSet.DualLineup)
'TODO: This line of code loads data into the 'MeetDataSet.EventList' table. You can move, or remove it, as needed.
Me.EventListTableAdapter.Fill(Me.MeetDataSet.EventList)
'DualLineupDataGridView.Columns(5).DefaultCellStyle.Format = ("mm\:ss\.ff")
MeetDataSet.DualLineup.Columns("AvgTime").Expression = "(([Time1] + [Time2]) /2)"
End Sub
Private Sub Sub_Btn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Sub_Btn.Click
Try
Me.Validate()
Me.DualLineupBindingSource.EndEdit()
Me.DualLineupTableAdapter.Update(Me.MeetDataSet.DualLineup)
MsgBox("Update successful")
Catch ex As Exception
MsgBox("Update failed")
End Try
End Sub
'Private Sub DualLineupDataGridView_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DualLineupDataGridView.CellFormatting
' If ((e.ColumnIndex = 5) AndAlso (Not IsDBNull(e.Value))) Then
' Dim tp As TimeSpan = CType(e.Value, TimeSpan)
' Dim dt As DateTime = New DateTime(tp.Ticks)
' e.Value = dt.ToString("mm\:ss\.ff")
' End If
'End Sub
'Private Sub DualLineupDataGridView_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DualLineupDataGridView.CurrentCellDirtyStateChanged
' If ((e.ColumnIndex = 5) AndAlso (Not IsDBNull(e.Value))) Then
' Dim tp As TimeSpan = CType(e.Value, TimeSpan)
' Dim dt As DateTime = New DateTime(tp.Ticks)
' e.Value = dt.ToString("mm\:ss\.ff")
' End If
'End Sub
End Class

AB,
If you're ok with your database other than working out this issue with time, you might want to give the following a try. It's pretty flexible in that you can give it a string or a decimal, and I'll explain:
The string can be in the format of "mm:ss" (minutes and seconds) or in the format of "mm:ss:f~".
The reason that I put the tilda there is because you're not limited on the number of decimal places - it will work out the math to figure out what you meant.
Also though, you can give it a decimal value representing the total number of seconds. Do be sure to clearly denote that it's a decimal type (otherwise it will assume it's a double and will fail). Here's the class:
Public Class SwimmerTime
Private _totalSeconds As Decimal
Public Sub New(ByVal value As Object)
Try
Dim tSeconds As Decimal = 0
If TypeOf value Is String Then
Dim s As String = CType(value, String)
If Not s.Contains(":"c) Then
Throw New ArgumentException("The string is malformed and cannot be used.")
Else
Dim elements() As String = s.Split(":"c)
For Each element As String In elements
If Not Integer.TryParse(element, New Integer) Then
Throw New ArgumentException("The string is malformed and cannot be used.")
End If
Next
If elements.Length = 2 Then
tSeconds = (60 * CInt(elements(0)) + CInt(elements(1)))
ElseIf elements.Length = 3 Then
tSeconds = (60 * CInt(elements(0)) + CInt(elements(1)))
Dim divideByString As String = "1"
For Each c As Char In elements(2)
divideByString &= "0"
Next
tSeconds += CDec(elements(2)) / CInt(divideByString)
Else
Throw New ArgumentException("The string is malformed and cannot be used.")
End If
End If
ElseIf TypeOf value Is Decimal Then
Dim d As Decimal = DirectCast(value, Decimal)
tSeconds = d
Else
Throw New ArgumentException("The type was not recognizable and cannot be used.")
End If
If tSeconds = 0 Then
Throw New ArgumentOutOfRangeException("Total Seconds", "Must be greater than zero.")
Else
_totalSeconds = tSeconds
End If
Catch ex As Exception
Throw
End Try
End Sub
Public Shared Function GetAverage(ByVal value1 As Object, _
ByVal value2 As Object) As SwimmerTime
Dim retVal As SwimmerTime = Nothing
Try
Dim st1 As SwimmerTime = New SwimmerTime(value1)
Dim st2 As SwimmerTime = New SwimmerTime(value2)
If st1 IsNot Nothing AndAlso st2 IsNot Nothing Then
Dim tempList As New List(Of Decimal)
With tempList
.Add(st1.TotalSeconds)
.Add(st2.TotalSeconds)
End With
Dim averageSeconds As Decimal = tempList.Average
retVal = New SwimmerTime(averageSeconds)
End If
Catch ex As Exception
Throw
End Try
Return retVal
End Function
Public ReadOnly Property FormattedString As String
Get
Dim ts As TimeSpan = TimeSpan.FromSeconds(_totalSeconds)
Return String.Format("{0:00}:{1:00}:{2:000}", _
ts.Minutes, _
ts.Seconds, _
ts.Milliseconds)
End Get
End Property
Public ReadOnly Property TotalSeconds As Decimal
Get
Return _totalSeconds
End Get
End Property
End Class
I'll show how to use it by example:
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Try
Dim averageSwimmerTime As SwimmerTime = _
SwimmerTime.GetAverage("02:24:05", 145.3274D)
MessageBox.Show(String.Format("Formatted String: {0}{1}Actual Value: {2}", _
averageSwimmerTime.FormattedString, vbCrLf, _
averageSwimmerTime.TotalSeconds), _
"Average Swimmer Time")
Stop
Catch ex As Exception
MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _
vbCrLf, ex.Message), "Program Error", _
MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
Stop
End Sub
End Class
An advantage here is that since it returns an instance of the class, you have access to the formatted string, and the actual decimal value.
I hope you find this helpful. :)
Still lost in code, just at a little higher level.

Similar Messages

  • WDA + AIF : Get modified PDF source (XSTRING) after user input

    Hi guys,
    I have this problem.
    I have an online adobe interactive form (ZCI layout) with fillable and dynamic attributes sets to 'X'.
    The interface is type "Dictionary Based" (not XML).
    I've created a wda that calls standard ADS function modules (FP_JOB_OPEN, generated function modules, FB_JOB_CLOSE) to get the xtring of this Form. Then i bind the xstring returned by generated function module in order to show it in a view (that contains an AIF element). Now the user can insert values in input-ready fields.
    When the user close the window, i'd like to read the whole (result) xstring of the pdf, filled with the user input.
    But when i read the context attached of the pdf (called pdfsource) after user input, it contains only the pdf source, but not the user's input also. The result should be a merge of pdfsource and userdata, in order to save the xstring in a specific path (after conversion).
    Is there a way to solve this problem ??
    Thank a lot for your help and hints
    Andrea

    Please,
    no one may help me with this task?
    Just know if it is possible do something like my request, or not.
    I've alredy search in old posts also, but nothig was found.
    Thanks a lot
    Andrea

  • How to cancelling email submission after user clicks "yes/no" button of message box?

    could some one tell me, how can i cancelling the submission event after one user clicks "yes/no" button of message box? The scenario is the following:
    After data input in a dynamic form clicks the user send mail button. Before the email submit, the user has to decide going back to the form and validate the input or continuing to submit email.
    In case of going back to validate input the submission event must not solve. So, how can i implemente it in java and/or form calc script?
    Thanks so much for your help in advance and i am very glad to hearing from you soon!
    Djinges

    Hello,
    The most easy way to solve your problem is to add two buttons, the first should be regular button and the second is submit by e-mail one. Set the
    'presence' property of the second to 'hidden' and add to it your email address. To the first button on 'click' event add the script like this
    form1.#subform[0].Button1::click - (JavaScript, client)
    var answer = xfa.host.messageBox("Send e-mail?","e-mail",2,1);
    if(answer==1){
    EmailSubmitButton1.execEvent('click');
    Hope this helps.

  • Interactive Gantt chart - how to receive updated XML after user changes

    Hello,
    I failed to receive changed XML after user updates.
    I've constructed following example:
    Created context attribute of type XSTRING, binded it to the "dataSource" property of the Gantt chart control.
    I pass following XML to the control:
    <?xml version="1.0" encoding="iso-8859-5" ?>
    <SAPJNetData version="1.0">
    <Application type="GANTT" version="1.0" />
    <TypeRepository version="1.0" href="/SAP/BC/WebDynpro/SAP/ZT_INV_WDR_TEST_GANTT/gantPR02P00086_3_tr.xml" />
    <UserInterface version="1.0" href="/SAP/BC/WebDynpro/SAP/ZT_INV_WDR_TEST_GANTT/gantPR02P00086_3_ui.xml" />
    <Graph type="Gantt.Graph" version="1.0">
    <rows>
      <row id="001" />
      <row id="002" />
      <row id="003" />
      </rows>
    <dates timeZone="GEurope/Berlin" locale="de_DE" format="dd.MM.yyyy" dateEnd="20.01.2010">
      <section date="01.01.2010" unit="DAY" unitSize="20" />
    <calendarItem id="Cal.1stDayInMonth">
      <repetition unit="MONTH" />
      </calendarItem>
    <calendarItem id="Cal.1stDayInWeek">
      <repetition unit="WEEK" />
      </calendarItem>
      </dates>
    <view>
      <viewpos date="01.01.2010" />
      </view>
    <chart id="Dummy">
    <timeScale>
    <section index="0">
      <ribbon type="Gantt.CProjects.Ribbon.Month" />
      <ribbon type="Gantt.CProjects.Ribbon.3Days" />
      </section>
      </timeScale>
      <grid type="Grid.CProjects.Gantt.TimeLine" calendarIDs="Cal.1stDayInWeek" />
    <table type="Gantt.Table" id="CProj-Table">
      <defaults typeCell="L.Table" typeHeader="L.Table" />
      <tree showRootIcons="TRUE" />
    <cols showInitially="4">
      <ids>TREE,ID2,ID3</ids>
      </cols>
    <header>
      <header width="30" />
      <label colid="TREE" width="250">Этап</label>
      <label colid="ID2">Дата с</label>
      <label colid="ID3">Дата по</label>
      </header>
    <rows>
      <ids>001,002,003</ids>
      </rows>
    <row>
      <header>1</header>
      <tree>Top Item</tree>
      <label>01.01.2010</label>
      <label>20.01.2010</label>
      </row>
    <row>
      <header>2</header>
      <tree parentRow="001">Subitem 1</tree>
      <label>01.01.2010</label>
      <label>10.01.2010</label>
      </row>
    <row>
      <header>3</header>
      <tree parentRow="001">Subitem 2</tree>
      <label>11.01.2010</label>
      <label>20.01.2010</label>
      </row>
      </table>
    <graph>
    <view>
      <backColor type="White" />
      </view>
    <node id="001" type="Gantt.CProjects.SummaryNode" rowID="001">
    <dates>
      <date>01.01.2010</date>
      <date>20.01.2010</date>
      </dates>
      </node>
    <node id="002" type="Gantt.CProjects.Node" rowID="002">
    <dates>
      <date>01.01.2010</date>
      <date>10.01.2010</date>
      </dates>
      </node>
    <node id="003" type="Gantt.CProjects.Node" rowID="003">
    <dates>
      <date>11.01.2010</date>
      <date>20.01.2010</date>
      </dates>
      </node>
      </graph>
      </chart>
      </Graph>
      </SAPJNetData>
    Then I run my example application, press standard "Save" button in Gantt chart control.
    After that my XML in context changes, but it's incorrect. There is no <graph> tag at all - this tag should contain all significant parameters of the chart.
    The resulting XML below:
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <SAPJNetData build="9295" date="04-Aug-2010 10:19:13" host="localhost" version="1.1247">
    <Application type="GANTT" version="1.0"/>
    <TypeRepository href="/SAP/BC/WebDynpro/SAP/ZT_INV_WDR_TEST_GANTT/gantPR02P00086_3_tr.xml" version="1.0"/>
    <UserInterface href="/SAP/BC/WebDynpro/SAP/ZT_INV_WDR_TEST_GANTT/gantPR02P00086_3_ui.xml" version="1.0"/>
    <GraphGantt version="1.1247"/>
    </SAPJNetData>
    All the chart in fact has completely disappeared. There is nothing left but file header.
    The question: How to get XML with all user changes back from the Gantt chart control?

    Long time, hah..
    Anyways thanks to behave like a responsible person on SCN and taking care of your threads..
    Liked.

  • How to call URL to collect user input ?

    Hi all,
    I am writing a Swing applications and at some points, I need to call a URL (external web page) to collect user input. It invokes passing certain parameters to web page so that the web page can be displayed in some certain form. After the user input all data in web page, press "submit", my Swing application needs to get the input back. I suppose that calling URL is trivial but how can I get the input back ? Any input will be greatly appreicated.
    Note: the web page will be displayed in one JFrame but it may not related to this problem.
    C.K.

    response.sendRediresc("http://.......);
    public void sendRedirect(java.lang.String location)
                      throws java.io.IOException
        Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root.
        If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to.
        Parameters:
            location - the redirect location URL
        Throws:
            java.io.IOException - If an input or output exception occurs
            java.lang.IllegalStateException - If the response was committed or if a partial URL is given and cannot be converted into a valid URL

  • How to determine which cell the user has just left?

    I want to check the contents of a JTable cell just after the user has left that cell.
    What is the most reliable way to determine which cell the user has just left?

    Hi,
    I use the cellRenderer for that... if the value is not correct, I call an editCellAt() method...
    JRG

  • How to Format DataTable Column after load Datatable without extra loop ??

    How to Format Column after load Datatable without extra loop ??
    I dont want to do extra logic which can cause performance thing.
    I have datatable which get fill from Dataset after database query, now i need to format column as decimal but without extra logic.
    I was thinking to create clone and than Import row loop but it ll kill performance, its WPF application.
    Thanks
    Jumpingboy

    You cannot do any custom things at all without doing some "extra logic". Formatting a number as decimal is certainly not a performance killer in any way whatsoever though.
    If you are displaying the contents of the DataTable in a DataGrid you could specify a StringFormat in the XAML:
    <DataGrid x:Name="dg1" AutoGenerateColumns="False">
    <DataGrid.Columns>
    <DataGridTextColumn Header="Number" Binding="{Binding num, StringFormat=N2}"/>
    </DataGrid.Columns>
    </DataGrid>
    Or if you are using auto-generated columns you could handle the AutoGeneratingColumn event:
    public MainWindow() {
    InitializeComponent();
    DataTable table1 = new DataTable();
    table1.Columns.Add(new DataColumn("num")
    DataType = typeof(decimal)
    table1.Rows.Add(1.444444444444);
    table1.Rows.Add(7.444444444444);
    dg1.ItemsSource = table1.DefaultView;
    dg1.AutoGeneratingColumn += dg1_AutoGeneratingColumn;
    void dg1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) {
    if (e.PropertyName == "num") {
    DataGridTextColumn column = e.Column as DataGridTextColumn;
    column.Binding.StringFormat = "N2";
    <DataGrid x:Name="dg1" />
     Please remember to mark helpful posts as answer and/or helpful.

  • How to display records that match user input date

    hi all,
      i need to display records that match user input date (i.e., for example if the difference between user input date and record date is less than 5 years then display those records) , this is for hr bw. any exit is there to check for validation for records to be displayed based on some abap coding.
    vijay

    I just see getApplication method but "Retrieves a list of all the deployed applications."
    My scenario is: I get user, end i want to discorver how application this user i enable to see.

  • How to close browser window after user log out

    Hi,
    Does anyone know how I can close browser window after user logs out. The scenario is when user clicks a log out button I will invalidate user session and close the browser right away in the backing bean.
    Your help would be appreciated.

    Try run this and you'll see that it runs fine with no exceptions:
    <%
         String someText = "bla bla bla";
         response.setContentType("text/plain");
         response.setHeader("Content-Disposition", "attachment;filename=message.txt");
         try {
              ServletOutputStream os = response.getOutputStream();
              os.write(someText.getBytes());
              os.flush();
              os.close();
         } catch (Exception e) {
              out.println("ERROR: " + e);
    %>It looks like that after I've closed the outputStream I can't do any more processing in the JSP. Even if I remove the setContentType and setHeader methods it still behaves this way.
    I'm starting to think that there's no way around this...??

  • How to check the value from user input in database or not?

    Hello;
    I want to check the value of user input from JtextFiled in my database or not.
    If it is in database, then i will pop up a window to tell us, otherwise, it will tell us it is not in database.
    My problem is my code do not work properly, sometimes, it tell me correct information, sometime it tell wrong information.
    Could anyone help,please.Thanks
    The following code is for check whether the value in database or not, and pop up a window to tell us.
    while( rs.next()) {
                    System.out.println("i am testing");
                    bInt=new Integer(rs.getInt("id"));
                    if(aInt.equals(bInt)){ // If i find the value in data base, set flag to 1.
                  flag=1;  //I set a flag to check whether the id in database or not
                        break;
             System.out.println("falg" + flag);
                if(flag==1){ //?????????????????????
              String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
              String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
              String remove3 = "DELETE FROM Customer WHERE id=" +a;
              s.executeUpdate(remove1);
              s.executeUpdate(remove2);
              s.executeUpdate(remove3);
                    JOptionPane.showMessageDialog(null,"you have success delete the value");
              s.close();
             else//???????????????????????????????
                  JOptionPane.showMessageDialog(null,"I could not found the value"); -------------------------------------------------------------------
    My whole program
    import java.sql.*;
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class DeleteC extends JFrame
        public static int index=0;   
        public static ResultSet rs;
        public static Statement s;
        public static Connection c;
        public static  Object cols[][];
        private static JTable table;
        private static JScrollPane scroller;
        private static int flag=0;
        public DeleteC()
            //information of our connection
            //the url of the database: protocol:subprotocol:subname:computer_name:port:database_name
            String strUrl      = "jdbc:oracle:thin:@augur.scms.waikato.ac.nz:1521:teaching";
            //user name and password
            String strUser      = "xbl1";
            String strPass      = "19681978";
            //try to load the driver
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            catch (ClassNotFoundException e) {
                System.out.println( "Cannot load the Oracle driver. Include it in your classpath.");
                System.exit( -1);
            //a null reference to a Connection object
            c = null;
            try {
                //open a connection to the database
                c = DriverManager.getConnection( strUrl, strUser, strPass);
            catch (SQLException e) {
                System.out.println("Cannot connect to the database. Here is the error:");
                e.printStackTrace();
                System.exit( -1);
           //create a statement object to execute sql statements
        public void getData(String a){
            try {
             //create a statement object to execute sql statements
             s = c.createStatement();
                int index=0;
                Integer aInt= Integer.valueOf(a);
                Integer bInt;
                  //our example query
                String strQuery = "select id from customer";
                //execute the query
                ResultSet rs = s.executeQuery( strQuery);
                //while there are rows in the result set
                while( rs.next()) {
                    System.out.println("i am testing");
                    bInt=new Integer(rs.getInt("id"));
                    if(aInt.equals(bInt)){
                  //JOptionPane.showMessageDialog(null,"I found the value"); 
                  flag=1;
                        break;
             System.out.println("falg" + flag);
                if(flag==1){
              String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
              String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
              String remove3 = "DELETE FROM Customer WHERE id=" +a;
              s.executeUpdate(remove1);
              s.executeUpdate(remove2);
              s.executeUpdate(remove3);
                    JOptionPane.showMessageDialog(null,"you have success delete the value");
              s.close();
             else
                  JOptionPane.showMessageDialog(null,"I could not found the value");
            catch (SQLException e) {
                 JOptionPane.showMessageDialog(null,"You may enter wrong id");
    My main program for user input from JTextField.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JOptionPane;
    import java.util.*;
    public class EnterID extends JFrame{
        public JTextField tF1;
        public EnterID enID;
        public String tF1Value;
        private JLabel label1, label2, label3;
        private static JButton button;
        private static ButtonHandler handler;
        private static String aString;
        private static Integer aInteger;
        private static Integer checkV=0;
        public static void main(String args[]){
           EnterID eId= new EnterID();
       public EnterID(){
          handler=new ButtonHandler();
          Container c= getContentPane();
          c.setLayout(new GridLayout(3,1));
          button= new JButton("ok");
          button.addActionListener(handler);
          label1 = new JLabel(" CustomerID, Please");
          label2 = new JLabel("Label2");
          label3 = new JLabel();
          label3.setLayout(new GridLayout(1,1));
          label3.add(button);
          label2.setLayout(new GridLayout(1,1));
          aString = "Enter Id Here";
          tF1 = new JTextField(aString);
          label2.add(tF1);
          c.add(label1);
          c.add(label2);         
          c.add(label3);            
          setSize(150,100);
          setVisible(true);     
       private class ButtonHandler implements ActionListener{
         public void actionPerformed(ActionEvent event){
             tF1Value=tF1.getText();
            //   CheckData cData = new CheckData();
             //  aInteger = Integer.valueOf(tF1Value);      
             if(tF1Value.equals(aString)){
              JOptionPane.showMessageDialog(null,"You didn't type value into box");
              setVisible(false); 
            else {
                DeleteC dC= new DeleteC();
                dC.getData(tF1Value);
                setVisible(false); 
    }

    You may have working code now, but the code you posted is horrible and I'm going to tell you a much much much better approach for the JDBC part. (You should probably isolate your database code from your user interface code as well, but I'm skipping over that structural problem...)
    Do this instead:
        public void getData(String a){
            PreparedStatement p;
            String strQuery = "select count(*) the_count from customer where id = ?";
            try {   
             //create a prepared statement object to execute sql statements, it's better, faster, safer
             p = c.prepareStatement(strQuery);
                // bind the parameter value to the "?"
                p.setInt(1, Integer.parseInt(a) );
                //execute the query
                ResultSet rs = p.executeQuery( );
                // if the query doesn't throw an exception, it will have exactly one row
                rs.next();
                System.out.println("i am testing");
                if (rs.getInt("the_count") > 0 ) {
                // it's there, do what you need to...
             else
                  JOptionPane.showMessageDialog(null,"I could not find the value");
            catch (SQLException e) {
                 // JOptionPane.showMessageDialog(null,"You may enter wrong id");
                 // if you get an exception, something is really wrong, and it's NOT user error
            // always, always, ALWAYS close JDBC resources in a finally block
            finally
                p.close();
        }First, this is simpler and easier to read.
    Second, this retrieves just the needed information, whether or not the id is in the database. Your way will get much much slower as more data goes into the database. My way, if there is an index on the id column, more data doesn;t slow it down very much.
    I've also left some important points in comments.
    No guarantees that there isn't a dumb typo in there; I didn't actually compile it, much less test it. It's at least close though...

  • On MacBook Pro, trashing anything requires password. How to fix so it doesn't. Also, finder window won't reopen in same place. How to fix?

    On my MacBook Pro, trashing files and folders requires that I input my password. How do I fix it so that I don't have to do that every time? Also, finder windows won't reopen in same place and configuration that I left them in when I closed them. How do I fix this?

    My guess is that you are storing your files on the root level of your HD. If so, move the files in to your user folder and you shouldn't get password prompts.
    Once you close a finder window you cannot continue that session. You can set the default location that a finder window opens however. Click on the finder, from the menubar select FInder/Preferences then click on the "General" tab. Where it says "New Finder windows open", you can select any folder on your drive as the default. My sggestion would be to set it to your User folder where you should be storing your files.

  • How can I manipulate a parameter value after user input

    Post Author: fsu304
    CA Forum: Crystal Reports
    I have a parameter that is used in my sql command and I want to be able to change the value of it if it reach a certian criteria.  For example the user enters the string "FDT" i want to change the parameter to equal "7" before it gets sent to the database to gather the records.  How can I accomplish this??
    Any help would be awesome.
    Heath

    Post Author: yangster
    CA Forum: Crystal Reports
    the easiest way to achieve this would be to create a lookup table that represents the value you have entered to mean something else in your primary selectionso your table would be a simple value, descriptionthe parameter the user enters 'FDT' = 7 in the table, it is then joined back to your initial queary and will only return you results for 7you can't create if statements with a commandand you cannot use a case statement with a parameterthe other alternative would be to write a procedure that takes in your value and converts it then runs your sql

  • How to regenerate additional rows after user clicks enter?

    Hi all,
              I am outputing the data through internal table(contains two fields 'Country' and 'Test')using ALV Classes.
    My requirement is user can add another row.And
    after appending another row user will enter country(say India) against the country
    field and clicks enter.Then the program has to fetch all the tests(say 'test1' and 'test2'  are there
    for India) described for India from the database table and refresh the screen
    with this additonal 2 rows(India, Test1 and India,Test2).
    Can anyone please let me know how to do it?Remember I am using ALV Classes.
    Thanks,
    Balaji.

    Hello Balaji
    I would use a simplified approach by storing the PBO output before displaying the editable ALV list. As soon as the user wants to save the data (enter 'SAVE' in command window) the report compares the PBO data with the current PAI data.
    To see the effect simply add a single row as previously described (resulting in three new rows) and delete two other rows. Inserted and deleted rows will be displayed afterwards.
    *& Report  ZUS_SDN_ALVGRID_EDITABLE_7
    REPORT  zus_sdn_alvgrid_editable_7.
    TYPE-POOLS: abap.
    INCLUDE <icon>.  " NOTE: replace by TYPE-POOLS: icon. on >= 6.20
    DATA:
      gd_repid         TYPE syrepid,
      gd_okcode        TYPE sy-ucomm,
      gs_layout        TYPE lvc_s_layo,
      gt_fcat          TYPE lvc_t_fcat,
      go_docking       TYPE REF TO cl_gui_docking_container,
      go_grid          TYPE REF TO cl_gui_alv_grid.
    TYPES: BEGIN OF ty_s_outtab.
    INCLUDE TYPE knb1.
    TYPES: END OF ty_s_outtab.
    TYPES: ty_t_outtab    TYPE STANDARD TABLE OF ty_s_outtab
                          WITH DEFAULT KEY.
    DATA:
      gt_outtab        TYPE ty_t_outtab,
      gt_outtab_pbo    TYPE ty_t_outtab.
    *       CLASS lcl_eventhandler DEFINITION
    CLASS lcl_eventhandler DEFINITION.
      PUBLIC SECTION.
        CLASS-METHODS:
          handle_data_changed
            FOR EVENT data_changed OF cl_gui_alv_grid
            IMPORTING
              er_data_changed
              e_onf4
              e_onf4_before
              e_onf4_after
              e_ucomm
              sender,
          handle_data_changed_finished
            FOR EVENT data_changed_finished OF cl_gui_alv_grid
            IMPORTING
              e_modified
              et_good_cells,
          handle_user_command
            FOR EVENT user_command OF cl_gui_alv_grid
            IMPORTING
              e_ucomm,
          handle_toolbar
            FOR EVENT toolbar OF cl_gui_alv_grid
            IMPORTING
              e_object
              e_interactive.
    ENDCLASS.                    "lcl_eventhandler DEFINITION
    *       CLASS lcl_eventhandler IMPLEMENTATION
    CLASS lcl_eventhandler IMPLEMENTATION.
      METHOD handle_data_changed.
    *   define local data
    **    cl_gui_cfw=>set_new_ok_code( 'REFRESH' ). " not possible on 4.6c
        CALL METHOD cl_gui_cfw=>set_new_ok_code
          EXPORTING
            new_code = 'REFRESH'
    *      IMPORTING
    *        RC       =
      ENDMETHOD.                    "handle_data_changed
      METHOD handle_data_changed_finished.
    *   define local data
        DATA:
          ls_outtab      TYPE ty_s_outtab,
          ls_cell        TYPE lvc_s_modi.
      ENDMETHOD.                    "handle_data_changed_finished
      METHOD handle_user_command.
      ENDMETHOD.                    "handle_user_command
      METHOD handle_toolbar.
    *   define local data
        DATA:
          ls_button    TYPE stb_button.
        ls_button-function  = 'DEFAULT'.
        ls_button-icon      = icon_mass_change.
        ls_button-quickinfo = 'Set default value for column'.
        APPEND ls_button TO e_object->mt_toolbar.
      ENDMETHOD.                    "handle_toolbar
    ENDCLASS.                    "lcl_eventhandler IMPLEMENTATION
    START-OF-SELECTION.
      SELECT * FROM knb1 INTO TABLE gt_outtab UP TO 20 ROWS
        WHERE bukrs = '1000'.
      gt_outtab_pbo = gt_outtab.  " store PBO data
    * Create docking container
      CREATE OBJECT go_docking
        EXPORTING
          parent                      = cl_gui_container=>screen0
          ratio                       = 90
        EXCEPTIONS
          OTHERS                      = 6.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    * Create ALV grid
      CREATE OBJECT go_grid
        EXPORTING
          i_parent          = go_docking
        EXCEPTIONS
          OTHERS            = 5.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    * Build fieldcatalog
      PERFORM build_fieldcatalog.
      PERFORM set_layout.
      SET HANDLER:
        lcl_eventhandler=>handle_toolbar               FOR go_grid,
        lcl_eventhandler=>handle_data_changed          FOR go_grid,
        lcl_eventhandler=>handle_data_changed_finished FOR go_grid.
    * Display data
      CALL METHOD go_grid->set_table_for_first_display
        EXPORTING
          is_layout       = gs_layout
        CHANGING
          it_outtab       = gt_outtab
          it_fieldcatalog = gt_fcat
        EXCEPTIONS
          OTHERS          = 4.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      go_grid->set_toolbar_interactive( ).
      CALL METHOD go_grid->register_edit_event
        EXPORTING
          i_event_id = cl_gui_alv_grid=>mc_evt_enter
        EXCEPTIONS
          error      = 1
          OTHERS     = 2.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    * Link the docking container to the target dynpro
      gd_repid = syst-repid.
      CALL METHOD go_docking->link
        EXPORTING
          repid                       = gd_repid
          dynnr                       = '0100'
    *      CONTAINER                   =
        EXCEPTIONS
          OTHERS                      = 4.
      IF sy-subrc <> 0.
    *   MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    * ok-code field = GD_OKCODE
      CALL SCREEN '0100'.
    * Flow logic (no elements on screen):
    *  PROCESS BEFORE OUTPUT.
    *    MODULE STATUS_0100.
    *  PROCESS AFTER INPUT.
    *    MODULE USER_COMMAND_0100.
    END-OF-SELECTION.
    *&      Module  STATUS_0100  OUTPUT
    *       text
    MODULE status_0100 OUTPUT.
      SET PF-STATUS 'STATUS_0100'.
    *  SET TITLEBAR 'xxx'.
      CALL METHOD go_grid->refresh_table_display
    *      EXPORTING
    *        IS_STABLE      =
    *        I_SOFT_REFRESH =
        EXCEPTIONS
          finished       = 1
          OTHERS         = 2.
      IF sy-subrc <> 0.
    *     MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *                WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    ENDMODULE.                 " STATUS_0100  OUTPUT
    *&      Module  USER_COMMAND_0100  INPUT
    *       text
    MODULE user_command_0100 INPUT.
      TRANSLATE gd_okcode TO UPPER CASE.
    * Fetch changes on ALV grid
      go_grid->check_changed_data( ).
      CASE gd_okcode.
        WHEN 'BACK' OR
             'END'  OR
             'CANC'.
          SET SCREEN 0. LEAVE SCREEN.
        WHEN 'REFRESH'.
          PERFORM refresh_outtab.
        WHEN 'SAVE'.
          PERFORM save_data.
        WHEN OTHERS.
      ENDCASE.
      CLEAR: gd_okcode.
    ENDMODULE.                 " USER_COMMAND_0100  INPUT
    *&      Form  BUILD_FIELDCATALOG_KNB1
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM build_fieldcatalog .
    * define local data
      DATA:
        ls_fcat        TYPE lvc_s_fcat.
      CALL FUNCTION 'LVC_FIELDCATALOG_MERGE'
        EXPORTING
    *     I_BUFFER_ACTIVE              =
          i_structure_name             = 'KNB1'
    *     I_CLIENT_NEVER_DISPLAY       = 'X'
    *     I_BYPASSING_BUFFER           =
    *     I_INTERNAL_TABNAME           =
        CHANGING
          ct_fieldcat                  = gt_fcat
        EXCEPTIONS
          inconsistent_interface       = 1
          program_error                = 2
          OTHERS                       = 3.
      IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      " Set required fields editable
      LOOP AT gt_fcat INTO ls_fcat
                      WHERE ( fieldname = 'ZUAWA'  OR
                              fieldname = 'BUSAB' ).
        ls_fcat-edit    = abap_true.
        MODIFY gt_fcat FROM ls_fcat.
      ENDLOOP.
      DELETE gt_fcat WHERE ( fieldname = 'ZINRT' ).
    ENDFORM.                    " BUILD_FIELDCATALOG
    *&      Form  SET_LAYOUT
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM set_layout .
      CLEAR: gs_layout.
      gs_layout-cwidth_opt = abap_true.
      gs_layout-zebra      = abap_true.
    **  gs_layout-stylefname = 'CELLTAB'.
    ENDFORM.                    " SET_LAYOUT
    *&      Form  REFRESH_OUTTAB
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM refresh_outtab .
    * define local data
      DATA:
        ld_idx       TYPE i,
        ls_outtab    TYPE ty_s_outtab,
        ls_tmp       TYPE ty_s_outtab,
        lt_tmp       TYPE ty_t_outtab.
      " Simulate selection of data depending on value of ZUAWA
      ls_tmp-zuawa = '003'.
      ls_tmp-busab = 'K1'.  APPEND ls_tmp TO lt_tmp.
      ls_tmp-busab = 'K2'.  APPEND ls_tmp TO lt_tmp.
      ls_tmp-busab = 'K3'.  APPEND ls_tmp TO lt_tmp.
      LOOP AT gt_outtab INTO ls_outtab
                        WHERE ( zuawa = '003'
                        AND     busab IS INITIAL ).
        ld_idx = syst-tabix.
        LOOP AT lt_tmp INTO ls_tmp.
          ls_outtab-busab = ls_tmp-busab.
          IF ( syst-tabix = 1 ).
            MODIFY gt_outtab FROM ls_outtab INDEX ld_idx.
          ELSE.
            APPEND ls_outtab TO gt_outtab.
          ENDIF.
        ENDLOOP.
      ENDLOOP.
    ENDFORM.                    " REFRESH_OUTTAB
    *&      Form  SAVE_DATA
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM save_data .
    * define local data
      DATA:
        ls_outtab    TYPE ty_s_outtab,
        ls_pbo       TYPE ty_s_outtab,
        lt_insert    TYPE ty_t_outtab,
        lt_delete    TYPE ty_t_outtab.
    " Compare PBO with PAI -> find deleted records
      LOOP AT gt_outtab_pbo INTO ls_pbo.
        READ TABLE gt_outtab INTO ls_outtab
             WITH KEY table_line = ls_pbo.
        IF ( syst-subrc NE 0 ).
          APPEND ls_outtab TO lt_delete.
        ENDIF.
      ENDLOOP.
    " Compare PAI with PBO data -> find new records
      LOOP AT gt_outtab INTO ls_outtab.
        READ TABLE gt_outtab_pbo INTO ls_pbo
             WITH KEY table_line = ls_outtab.
        IF ( syst-subrc NE 0 ).
          APPEND ls_outtab TO lt_insert.
        ENDIF.
      ENDLOOP.
      CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY_LVC'
        EXPORTING
          i_structure_name = 'KNB1'
          i_grid_title     = 'New Records'
        TABLES
          t_outtab         = lt_insert
        EXCEPTIONS
          program_error    = 1
          OTHERS           = 2.
      IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY_LVC'
        EXPORTING
          i_structure_name = 'KNB1'
          i_grid_title     = 'Deleted Records'
        TABLES
          t_outtab         = lt_delete
        EXCEPTIONS
          program_error    = 1
          OTHERS           = 2.
      IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      gt_outtab_pbo = gt_outtab.  " do not forget !!!
    ENDFORM.                    " SAVE_DATA
    Regards
      Uwe

  • How to format a cell in a second table to show m3 as m³

    I can make an "own format" but I need it too often.
    So it will be much work.
    After I change the first cell to other text, the "own format" wil be shown a wrong Text in this second table-cell.
    So, how else?

    To get the number in to superscript you can use the keys Ctrl + Cmd + plus sign. Press the keys just before writing the number and then gain just after to get the coming text in normal format
    I am not sure I understood all of your post. If there is another hidden question please repeat it.

  • How to calculate the total from users input in switch?

    I dont know how to hold the input from user. But here is part of my coding :
    System.out.println ("Type 1 for buying Ruler"+
    "\nType 2 for buying Pencil");
    stationaries = console.nextInt();
    switch (stationaries)
    case 1 : System.out.println("Ruler per unit : MYR1");
    System.out.println("How much does you want? : ")
    wantRuler = console.nextInt();
    sum = wantRuler * 1;
    break;
    case 2 : System.out.println("Pencil per unit : MYR2");
    System.out.println("How much does you want? : ")
    wantPencil = console.nextInt();
    sum = wantPencil * 2;
    break;
    How can I calculate the total for both of the stationaries if user wants 5 for ruler and 6 for pencil?

    Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.

Maybe you are looking for

  • A image with a drop shadow on a shaded background

    When I make a copy from my color printer of my PDF that has a image with a grey drop shadow on a grey shaded background. I get a shaded box around the image. This does not happen when I print from my b&w laser printer. The PDF was exported from Indes

  • Intel Mac Mini networked to G4?

    Hi there! Can I connect the new Intel Mac mini to a network containing an old Mac G4 dual running OSX.3.9, and if so will I be able to access files from either computer despite the different operating systems? Also, can I install and run all my old o

  • 20gb of Disk Space Vanishes? On it's own?

    Hi guys, I'm a long time mac user and have never seen anything like this. I run a 2.53gz MBP 5,1. with 4gb of ram and 320gb HD. I have the drive partitioned with a 60gb NTFS bootcamp partition for WindowsXP that I use with Parallels 4. I use Time Mac

  • Safari bunches words in web pages

    I have Safari 4.0.3 and I have been having trouble with web pages such as foxnews.com and espn.com where all of the word are bunched together. in foxnews.com the descriptions of the pictures are dropped down into the main part of the article, espn.co

  • DAQ Chat Support 'Beta' Program

    I tried the: Chat with an Engineer! Try out our LabVIEW Chat Support and DAQ Chat Support Beta Program Is there anyone at the other end?  I've been waiting 2 hours and nothing...  It just says "Waiting for technician" R