Deleting a row from matrix by context menu

Hi all
does anyone know how can i cause right click on mouse button. on a certain row within a matrix to show a context menu with the option to delete the row. and when pressing the menu item handling the event of deleting the row from the matrix?
appreciate the help
Yoav

Hi Yoav,
Simply, 'context menu' have to be handled with 'menu event' object.
It can be done by 'flushToDataSource' method and some tricks.
Basically, method delete the row without any clause of addon code.
But it's only can be done in display side.
If you're using DBDataSource, you have to flush to the datasource.
I mean, you have to update datasource with the data displayed in the matrix.
and then, delete the last row of the datasource.
FlushToDataSource doesn't affect to the number of rows in the datasource.
You have to delete a row with a method of DBDatasource.. I can't remember the name.
If, the matrix uses userdatasource, you don't need to delete a row in datasource.
Because userdatasource doesn't have a concept of 'row', actually.
Hope this helpful for you.
Regards,
Hyunil Choi

Similar Messages

  • Delete datagridview row using right click context menu does not behave like the delete key

    I have a datagridview with editing enabled. If I click the row header and press the delete key, the row is removed no questions asked. I don't recall doing any coding to make this happen but I couldn't do copy and paste using keys so I created a context
    menu with copy, paste, & delete.  The delete option calls
    dgvVX130.Rows.RemoveAt(dgvVX130.SelectedRows[0].Index);
    The row is removed but the problem is this fires other events like RowValidating which fails.  I presume because the row is no longer there.
    The delete keypress is definitely a lot cleaner so my question is 3fold. 
    1) Why doesn't Rows.RemoveAt behave like the delete key? 
    2) Is it possible to issue a delete keypress to do the same thing?
    3)  Is it possible to suppress the RowValidating event or other events when Rows.RemoveAt is fired?

    Interesting.  My delete key does not fire the row validating event.  When I use the delete key I click on the row header which does fire the row validating event and then I press the delete key.  Row is deleted and no event fires.  Works
    just the way I want it to.  I wish my context menu delete worked that way.  I wouldn't know what chunk of code I can provide to show the Row Validating NOT firing when delete key is pressed but here is the context menu code that does fire Row Validating.
    private void cmsEditItemClick(object sender, ToolStripItemClickedEventArgs e)
    ToolStripItem item = e.ClickedItem;
    switch (item.Text)
    case "Copy":
    if (dgvVX130.GetCellCount(DataGridViewElementStates.Selected) > 0)
    try
    // Add the selection to the clipboard.
    Clipboard.SetDataObject(
    dgvVX130.GetClipboardContent());
    // Replace the text box contents with the clipboard text.
    catch (System.Runtime.InteropServices.ExternalException)
    MessageBox.Show("The Clipboard could not be accessed. Please try again.");
    break;
    case "Paste":
    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
    ClipboardUtils.PasteFromClipboard(dgvVX130);
    dgvVX130.NotifyCurrentCellDirty(true);
    dgvVX130.EndEdit();
    dgvVX130.NotifyCurrentCellDirty(false);
    bindingSource1_PositionChanged(this, e);
    break;
    case "Delete":
    dgvVX130.Rows.RemoveAt(dgvVX130.SelectedRows[0].Index);
    break;
    default:
    //code
    break;
    private void dgvVX130CellContentClick(object sender, DataGridViewCellEventArgs e)
    //dgvVX130.IsUserSelectionEnabled = true;
    dgvVX130.BeginEdit(false);
    ((TextBox)dgvVX130.EditingControl).SelectionStart = 0;
    //((TextBox)dgvVX130.EditingControl).SelectionLength = 3;
    public class ClipboardUtils
    public static void PasteFromClipboard(DataGridView grid)
    try
    char[] rowSplitter = { '\r', '\n' };
    char[] columnSplitter = { '\t' };
    // Get the text from Clipboard
    IDataObject dataInClipboard = Clipboard.GetDataObject();
    string stringInClipboard = (string)dataInClipboard.GetData(DataFormats.StringFormat);
    // split into rows
    string[] rowInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);
    // get current cell
    int currentRow = grid.SelectedCells[0].RowIndex;
    int currentColumn = grid.SelectedCells[0].ColumnIndex;
    // get 1st cell in selected area
    for (int i = 1; i < grid.SelectedCells.Count; i++)
    if (currentRow > grid.SelectedCells[i].RowIndex)
    currentRow = grid.SelectedCells[i].RowIndex;
    if (currentColumn > grid.SelectedCells[i].ColumnIndex)
    currentColumn = grid.SelectedCells[i].ColumnIndex;
    // add more rows if need to paste data
    /* if (grid.Rows.Count < rowInClipboard.Length + currentRow)
    grid.Rows.Add(rowInClipboard.Length + currentRow - grid.Rows.Count); */
    // paste
    for (int iRow = 0; iRow < rowInClipboard.Length; iRow++)
    if (iRow + currentRow < grid.Rows.Count)
    string[] cellsInRow = rowInClipboard[iRow].Split(columnSplitter);
    for (int iCol = 0; iCol < cellsInRow.Length; iCol++)
    if (grid.ColumnCount > currentColumn + iCol)
    DataGridViewCell currentCell = grid.Rows[currentRow + iRow].Cells[currentColumn + iCol];
    if (!currentCell.ReadOnly) // H.NH added to avoid Read only case.
    if (cellsInRow[iCol] == "")
    if (grid.Columns[iCol].ValueType.Name == "String")
    currentCell.Value = null;
    else
    currentCell.Value = DBNull.Value;
    else
    currentCell.Value = cellsInRow[iCol];
    switch (iCol)
    case 3:
    currentCell.Value += "_ChangeColumnName";
    break;
    case 2:
    currentCell.Value = grid.Rows[iRow].Cells[iCol].Value;
    break;
    else break;
    catch (Exception e)
    MessageBox.Show("Sorry, can not paste from the clipboard.\nError: " + e.Message, "Paste Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

  • DELETE MULTIPLE ROWS FROM MATRIX

    Hi all,
    I´M DESPERATED.
    I am able to delete row by row in my matrix, but ¿Could anyone post a sample to delete multiple rows?
    I´ve been trying several ways but it doesn´t work.
    My code is:
    ========================
      Dim i As Long = oMatrix.GetNextSelectedRow
                    If i > -1 Then
                        If oMatrix.IsRowSelected(i) = True Then
                            oMatrix.DeleteRow(i)
                        End If
    ========================
    Thank you in advanced,
    lorenzo

    Don´t worry, It was a problem with my loop.
    Thanks anyway
    lorenzo

  • Deleting a row from a table control through right-clic​k menu

    I have a table control. I want to delete a row from it when a user right clicks on a particular row and selects "Delete row" menu item. I have managed the creation of menu item but have not been able to delete the row which is right clicked and the menu item "Delete row" is selected. Guidance required! Thanks!

    smercurio_fc wrote:
    It's irrelevant whether the table is a control or indicator. See attached VI.
    Hi smercurio,
    please see the attached picture. In my previous post i mean the different in the menu. The red marked function is not available, if the table is an indicator. LV8.5!
    Mike
    Message Edited by MikeS81 on 04-18-2008 05:19 PM
    Attachments:
    Unbenannt.PNG ‏22 KB

  • Deleting a row from a Row Repeater

    Hi All,
    How could i delete a row from a row repeater??????
    I am using REMOVE_ELEMENT method from IF_WD_CONTEXT_NODE interface... Is this the correct way!!!!!!.
    Is there anyother way to do the same?????
    Best Regards.
    Shafiq Ahmed Khan.

    Hi
    first u get the index from the context element. with the help of the index u can get that particular element using get element.
    then u remove the element .
    check this code.
    CALL METHOD context_element->get_index
      receiving
        my_index = lv_index.
    CALL METHOD lo_nd_rcf_edu_det->get_element
      EXPORTING
        index        = lv_index
      receiving
        node_element = lo_el_rcf_edu_det .
    CALL METHOD lo_nd_rcf_edu_det->remove_element
      EXPORTING
        element          = lo_el_rcf_edu_det
    receiving
       has_been_removed =
    Declare a parameter context_element in the method of type if_wd_context_element
    regards
    chythanya

  • Issue while deleting a row from a table

    Dear friends,
    i am getting an issue while deleting a row from a table, pls check screen shots , the first screen shot is my table contents
    when i delete 2 row , the second row is deleting properly like below screen shot
    but i want like below screen shot , Col1 contents should be like pic 1 . could any one pls let me know how to solve this issue.
    Thanks
    Vijaya

    Hi vijaya,
    please try this code, it will help you.
    DATA : it_rows  TYPE wdr_context_element_set,
              wa_rows LIKE LINE OF it_rows.
       DATA lo_nd_table TYPE REF TO if_wd_context_node.
        DATA lt_table TYPE wd_this->elements_table.
       DATA lo_el_table TYPE REF TO if_wd_context_element.
       DATA ls_vbap TYPE wd_this->element_table.
    DATA: ld_index TYPE i.
    data value TYPE sy-index.
    * navigate from <CONTEXT> to <table> via lead selection
       lo_nd_table= wd_context->get_child_node( name = wd_this->wdctx_table ).
    * @TODO handle non existant child
    * IF lo_nd_table IS INITIAL.
    * ENDIF.
    * get element via lead selection
    * alternative access  via index
    * lo_el_table = lo_nd_table->get_element( index = 1 ).
    * @TODO handle not set lead selection
       IF lo_el_table IS INITIAL.
       ENDIF.
    * navigate from <CONTEXT> to <table> via lead selection
       lo_nd_table = wd_context->get_child_node( name = wd_this->wdctx_table ).
    * @TODO handle non existant child
    * IF lo_nd_table IS INITIAL.
    * ENDIF.
       lo_nd_table->get_static_attributes_table( IMPORTING table = lt_table ).
    * @TODO handle non existant child
    * IF lo_nd_table IS INITIAL.
    * ENDIF.
    ** @TODO compute values
    ** e.g. call a model function
    * navigate from <CONTEXT> to <table> via lead selection
       lo_nd_table = wd_context->get_child_node( name = wd_this->wdctx_table ).
    * @TODO handle non existant child
    * IF lo_nd_table IS INITIAL.
    * ENDIF.
    ** @TODO compute values
    ** e.g. call a model function
    it_rows  =  lo_nd_table>get_selected_elements( ).
       CALL METHOD lo_nd_table->GET_LEAD_SELECTION_INDEX
       RECEIVING
         INDEX  = value .
      LOOP AT it_rows INTO wa_rows.
         CALL METHOD wa_rows->get_static_attributes
           IMPORTING
                  static_attributes = ls_table.
         READ TABLE lt_table INTO ls_table WITH KEY col1 = ls_table-col1.
          ld_index = value.
              ENDLOOP.
       CLEAR : ls_table-col2,
             ls_table-col2.
       MODIFY lt_table INDEX ld_index FROM ls_table.
      lo_nd_table->bind_table( new_items = lt_table set_initial_elements = abap_true ).

  • Delete Last Row in Matrix on SBO 2005

    Hi,
    Im using SAPB1 2005 SP1 with B1DE.
    I've seen a post that indicates that the following code should delete a row from a matrix (even the last row) when using SBO 2005
    I still find that all rows except last row of matrix are removed from the database.
    <b>How do I delete the last row from the Del button event handler????</b>
    I'm using
    <i>        [B1Listener(BoEventTypes.et_CLICK, false)]
            public virtual void OnAfterClick(ItemEvent pVal)
                bool ActionSuccess = pVal.ActionSuccess;
                Form form = B1Connections.theAppl.Forms.Item(pVal.FormUID);
                Item item = form.Items.Item("del");
                Button button = ((Button)(item.Specific));
                // ADD YOUR ACTION CODE HERE ...
                int row;
                Matrix oMtx = (Matrix)form.Items.Item("mtx_0").Specific;
                DBDataSource oDBDS = (DBDataSource)form.DataSources.DBDataSources.Item("@SD_POOLCONTRCT_LINE");
                row = oMtx.GetNextSelectedRow(0, BoOrderType.ot_SelectionOrder);
                oMtx.DeleteRow(row);
                if (oMtx.RowCount == 0)
                    oDBDS.RemoveRecord(0);
                if ((form.Mode != BoFormMode.fm_ADD_MODE) | (form.Mode != BoFormMode.fm_UPDATE_MODE))
                    form.Mode = BoFormMode.fm_UPDATE_MODE;
                }</i>

    Hi Ben,
    [B1Listener(BoEventTypes.et_CLICK, false)]
    public virtual void OnAfterClick(ItemEvent pVal)
    bool ActionSuccess = pVal.ActionSuccess;
    Form form = B1Connections.theAppl.Forms.Item(pVal.FormUID);
    Item item = form.Items.Item("del");
    Button button = ((Button)(item.Specific));
    // ADD YOUR ACTION CODE HERE ...
    int row;
    Matrix oMtx = (Matrix)form.Items.Item("mtx_0").Specific;
    DBDataSource oDBDS = (DBDataSource)form.DataSources.DBDataSources.Item("@SD_POOLCONTRCT_LINE");
    Rest of your code will remain same.
    I am making the modification here. I am using the RowCount property that gives me the address of the last row of the matrix.
    <b>row = oMtx.RowCount;</b>
    Every time this will return you the last row and that row will be deleted.
    <b>row = oMtx.RowCount;</b>
    oMtx.DeleteRow(row);
    if (oMtx.RowCount == 0)
    oDBDS.RemoveRecord(0);
    if ((form.Mode != BoFormMode.fm_ADD_MODE) | (form.Mode != BoFormMode.fm_UPDATE_MODE))
    form.Mode = BoFormMode.fm_UPDATE_MODE;
    Regards,
    Prashant

  • Delete a row from a data object using an AQ-driven EMS

    Hello, technetwork.
    I need to show the contents of a table that changes frequently (inserts, updates and deletes) at ORDBMS 10g in my BAM dashboard.
    What i have done is:
    - Create two different queue tables, queues.
    - Create two triggers: one for "AFTER insert or UPDATE" and the other for "BEFORE DELETE".
    - Create two EMS, one configured to Upsert operations and the other to Delete.
    - The Upsert EMS works, but the Delete EMS does not.
    - Both EMS Metrics say that they work fine and commit the messages i send to the ADC.
    - Testing showed records are populated and updated in the ADC but never deleted.
    There is a detailed user case for "Creating an EMS Against Oracle Streams AQ JMS Provider" in the Fusion Midleware Developer's Guide for SOA Suite, but it deals only with Upserts. I am using the last versions of SOA suite and Weblogic. The official support has no information either.
    I hope writing a web service client isn't the only way to delete a row from a data object. Am i missing something? Any help will be much appreciated.
    My EMS config:
    Initial Context Factory: weblogic.jndi.WLInitialContextFactory.
    JNDI Service Provider URL: t3://<spam>:80.
    Topic/Queue Connection Factory Name: jms/BAMAQTopicCF.
    Topic/Queue Name: jms/ProdGlobalBAMD_flx.
    JNDI Username: .
    JNDI Password: .
    JMS Message Type: TextMessage.
    Durable Subscriber Name (Optional): BAM_ProdGlobalBAMD.
    Message Selector (Optional): .
    Data Object Name: /bam/ProdGlobalBAM_flx.
    Operation: Delete.
    Batching: No.
    Transaction: No.
    Start when BAM Server starts: No.
    JMS Username (Optional): .
    JMS Password (Optional): .
    XML Formatting
    Pre-Processing
    Message Specification
    Message Element Name: row
    Column Value
    Element Tag
    Attribute
    Source to Data Object Field Mapping
    Key Tag name Data Object Field
    . BARCODE. BarCode.
    Added my EMS config

    Ram_J2EE_JSF wrote:
    How to accomplish this using JavaScript?Using Javascript? Well, you know, Javascript runs at the client side and intercepts on the HTML DOM tree only. The JSF code is completely irrelevant. Open your JSF page in your favourite webbrowser and view the generated HTML source. Finally just base your Javascript function on it.

  • HOW TO DELETE THE ROW FROM DATABASE

    hI,
    Iam pasting my code below.My problem isi retrieve rows from database and display them in jsp page in rows.For each row there is delete hyperlink.Now when i click that link i should only delete the row corresponding to that delete link temporarily but it should not delete the row from database now.It should only delete the row from database when i click the save button.How can i do this can any one give some code.
    thanks
    naveen
    [email protected]
    <%@ page language="java" import="Utils.*,java.sql.*,SQLCon.ConnectionPool,java.util.Vector,java.util.StringTokenizer" %>
    <html>
    <head>
    <meta http-equiv="Content-Language" content="en-us">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
    <meta name="ProgId" content="FrontPage.Editor.Document">
    <title>Item Details</title>
    <script>
    function submitPage()
    document.details.action = "itemdetails.jsp" ;
    document.details.submit();
    </script>
    </head>
    <body>
    <form name="details" action="itemdetails.jsp" method="post">
    <%
    ConnectionPool pool;
    Connection con = null;
    Statement st;
    ResultSet rs =null;
    %>
    <table border="0" cellpadding="0" cellspacing="0" width="328">
    <tr>
    <td width="323" colspan="4"><b>Reference No :</b> <input type="text" name="txt_refno" size="14">
    <input type="submit" value="search" name="search" ></td>
    </tr>
    <tr>
    <td width="81" bgcolor="#000099"><font color="#FFFFFF"><b>Item Code</b></font></td>
    <td width="81" bgcolor="#000099"><font color="#FFFFFF"><b>Item No</b></font></td>
    <td width="81" bgcolor="#000099"><font color="#FFFFFF"><b>Amount </b></font></td>
    <td width="80" bgcolor="#000099"> </td>
    </tr>
    <%
    pool= new ConnectionPool();
    Utils utils = new Utils();
    double total =0.00;
    String search =utils.returnString(request.getParameter("search"));
    if(search.equals("search"))
    try
    String ref_no =utils.returnString(request.getParameter("txt_refno"));
    String strSQL="select * from ref_table where refno='" + ref_no + "' ";
    con = pool.getConnection();
    st=con.createStatement();
    rs = st.executeQuery(strSQL);
    while(rs.next())
    String itemcode=rs.getString(2);
    int item_no=rs.getInt(3);
    double amount= rs.getDouble(4);
    total= total + amount;
    %>
    <tr>
    <td width="81"><input type=hidden name=hitem value=<%=itemcode%>><%=itemcode%></td>
    <td width="81"><input type=hidden name=hitemno value=<%=item_no%>><%=item_no%></td>
    <td width="81"><input type=hidden name=hamount value=<%=amount%>><%=amount%></td>
    <td width="80"><a href="delete</td>
    </tr>
    <%
    }catch(Exception e){}
    finally {
    if (con != null) pool.returnConnection(con);
    %>
    <tr>
    <td width="323" colspan="4">
    <p align="right"><b>Total:</b><input type="text" name="txt_total" size="10" value="<%=total%>"></td>
    </tr>
    <tr>
    <td width="323" colspan="4">                   
    <input type="button" value="save" name="save"></td>
    </tr>
    </table>
    </form>
    </body>
    </html>

    You mean when you click on the hyperlink you want that row to disappear from the page, but not delete the row from the database until a commit/submit button is pressed?
    Personally, I think I'd prefer that you have a delete checkbox next to every row and NOT remove them from the display if I was a user. You give your users a chance to change their mind about their choice, and when they're done they can see exactly which rows will be deleted before they commit.
    You know your problem, of course, so you might have a good reason for designing it this way. But I'd prefer not removing them from the display. JMO - MOD

  • How to delete multiple rows from ADF table

    How to delete multiple rows from ADF table

    Hi,
    best practices when deleting multiple rows is to do this on the business service, not the view layer for performance reasons. When you selected the rows to delete and press submit, then in a managed bean you access thetable instance (put a reference to a managed bean from the table "binding" property") and call getSeletedRowKeys. In JDeveloper 11g, ADF Faces returns the RowKeySet as a Set of List, where each list conatins the server side row key (e.g. oracle.jbo.Key) if you use ADF BC. Then you create a List (ArrayList) with this keys in it and call a method exposed on the business service (through a method activity in ADF) and pass the list as an argument. On the server side you then access the View Object that holds the data and find the row to delte by the keys in the list
    Example 134 here: http://blogs.oracle.com/smuenchadf/examples/#134 provides you with the code
    Frank

  • Deleting a row from a Procedure

    Hi All
    Can one of you tell me how to delete a row from a Procedure
    It is created with
    CREATE OR REPLACE PROCEDURE report.NAMEOFTABLE
    (nPutId IN Report.ID%TYPE,
    cArea IN Report.Area%TYPE,
    cSubject IN Report.Subject%TYPE,
    nUserId IN Report.EngineerID%TYPE,
    cDesc IN Report.Description%TYPE,
    cSide IN Report.SideEffects%TYPE,
    cImpact IN Report.Impact%TYPE,
    cNotes IN Report.Notes%TYPE,
    nValid IN Report.Valid%TYPE) AS
    -- Add or update Report
    -- If nId < 1 then a record is added, otherwise updated.
    BEGIN
    IF nId < 1 THEN
    INSERT INTO Report
    (Area, Subject, EngineerID,
    Description, SideEffects, Impact,
    ReportNotes, Valid)
    VALUES
    (cArea, cSubject, nUserId, cDesc, cSide, cImpact, cNotes, nValid);
    ELSE
    UPDATE Report
    SET ReportArea = cArea,
    ReportSubject = cSubject,
    ReportDescription = cDesc,
    ReportSideEffects = cSide,
    ReportImpact = cImpact,
    ReportNotes = cNotes,
    ReportValid = nValid
    WHERE ReportID = nPutId;
    END IF;
    COMMIT;
    END;
    CREATE SYNONYM Admin.NAMEOFTABLE
    Report.NAMEOFTABLE;
    But I need to make 1 field of the impact and the sideEffect called the ImpactEffect
    So how do i delete the field of Side effect and change the name of the Impact field.
    Sould I make a new Procedure?

    If you want to delete a row, you'd need a DELETE statement. It is not obvious to me, though, that you really want to delete a row. It sounds like you're trying to update a row, and there is an UPDATE statement in the procedure. Unfortunately, I'm very unsure exactly what you're trying to accomplish and how this procedure relates to that goal. Perhaps if you could post the starting state of the row, the procedure call you're trying to make, and the end state of that row, things might be much clearer.
    As an aside, do you really have a schema and a table named REPORT? That seems rather confusing.
    Justin

  • Deleting a row from JTable

    I am trying to delete a row from a JTable whenever the button on the last column is pressed. I know to do this, I can use the removeRow(int) method of the tableModel. But the odd thing is when I try to get a handle to the TableModel from the JTable to use that function, i.e. table.getModel().removeRow(int) it doesn't work. But if I explicitly pass in the tableModel into my class it does work. Here's the code below:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.UIManager;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableCellEditor;
    import javax.swing.AbstractCellEditor;
    import javax.swing.table.DefaultTableModel;
    public class tester4 extends JFrame
         protected final int BUTTON_COL = 2;
         private TableCellRenderer defaultRenderer;
         private TableCellEditor defaultEditor;
         private JTable workingTable;
         private String[] transactionCols = {"Qty", "Product", "Cancel"};
         private Object[][] data = {{5, "prod1", "Cancel"},
                   {6, "prod2", "Cancel"},
                   {7, "prod3", "Cancel"}};
        public tester4()
              workingTable = new JTable(tableModel);
              workingTable.setName("Working Table");
              defaultRenderer = workingTable.getDefaultRenderer(JButton.class);
              defaultEditor = workingTable.getDefaultEditor(Object.class);
              StatusTableRenderer testRenderer = new StatusTableRenderer(defaultRenderer, defaultEditor, workingTable, tableModel);
              workingTable.setDefaultRenderer(Object.class, testRenderer);
              workingTable.setDefaultEditor(Object.class, testRenderer);
            JScrollPane scrollPane = new JScrollPane( workingTable );
            getContentPane().add( scrollPane );
         private DefaultTableModel tableModel = new DefaultTableModel(data, transactionCols){
              // Only allow button column to be editable, if there is an actual
              // button in that row          
              public boolean isCellEditable(int row, int col){
                   return (col == BUTTON_COL && data[row][col] != "") ? true : false;
              // Overriden getColumnClass method that will return the object
              // class type of the first instance of the data type otherwise
              // returns the Object.class
              public Class getColumnClass(int column){
                for (int row = 0; row < getRowCount(); row++){
                    Object o = getValueAt(row, column);
                    if (o != null){ return o.getClass(); }
                return Object.class;
        public static void main(String[] args)
            tester4 frame = new tester4();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        public class StatusTableRenderer extends AbstractCellEditor
                                                implements TableCellRenderer,
                                                               TableCellEditor,
                                                               ActionListener{
             private TableCellRenderer defaultRenderer;
             private TableCellEditor defaultEditor;
             private JButton cancelButton;
             private JButton editButton;
             private String text;
             private int buttonColumn;
             private int selectedRow;
             private JTable table;
             private DefaultTableModel tableModel;
             public StatusTableRenderer(TableCellRenderer renderer,
                                           TableCellEditor editor,
                                           JTable table,
                                           DefaultTableModel tableModel){
                  defaultRenderer = renderer;
                  defaultEditor = editor;
                  this.table = table;
                  this.tableModel = tableModel;
                  buttonColumn = table.getColumnCount() - 1;
                cancelButton = new JButton();
                editButton = new JButton();
                editButton.setFocusPainted(true);
                editButton.addActionListener(this);
             public StatusTableRenderer(TableCellRenderer renderer,
                                                TableCellEditor editor,
                                                JTable table,
                                                DefaultTableModel tableModel,
                                                int _buttonColumn){
                  this(renderer, editor, table, tableModel);
                  buttonColumn = _buttonColumn;
             public Component getTableCellRendererComponent(JTable table, Object value,
                       boolean isSelected, boolean hasFocus, int row, int column) {
                  if (column == buttonColumn){
                       if (hasFocus){
                            cancelButton.setForeground(table.getForeground());
                            cancelButton.setBackground(UIManager.getColor("Button.background"));
                       else if (isSelected){
                            cancelButton.setForeground(table.getSelectionForeground());
                            cancelButton.setBackground(table.getSelectionBackground());
                       else{
                            cancelButton.setForeground(table.getForeground());
                            cancelButton.setBackground(UIManager.getColor("Button.background"));
                       cancelButton.setText( (value == null) ? "" : value.toString() );
                       return cancelButton;
                return defaultRenderer.getTableCellRendererComponent(
                            table, value, isSelected, hasFocus, row, column);
             public Component getTableCellEditorComponent(JTable table, Object value,
                       boolean isSelected, int row, int column){
                  if (column == buttonColumn){
                       text = ((value == null) ? "": value.toString());
                       editButton.setText(text);
                       selectedRow = row;
                       return editButton;
                  return defaultEditor.getTableCellEditorComponent(
                            table, value, isSelected, row, column);
            public Object getCellEditorValue()
                return text;
            public void actionPerformed(ActionEvent e)
                fireEditingStopped();
                // This works
                tableModel.removeRow(selectedRow);
               // This does not work
              //  table.getModel().removeRow(selectedRow);
    }Take a look at the actionPerfformed method. One way of doing it works, one doesn't. Just trying to understand why me getting a handle to the tableModel through the table doesn't work.
    Message was edited by:
    deadseasquirrels

    It gives me a run-time error Well then your question should be "why do I get this run-time error" and then you would quote the error. Be more descriptive. "It doesn't work" is not descriptive.
    table.getModel().removeRow(selectedRow);I don't use JDK1.5 either. But if you are saying that the above line compiles cleanly with JDK1.5 (because of the auto-boxing feature, or whatever its called), then I see no reason why the code wouldn't work since it recognizes the class as a DefaultTableModel.
    Presumably you commented out the other line so you don't try to delete the row twice. Otherwise you might be getting a indexing error.

  • Deleting a row from a database...

    Here is the method I am calling to delete a row from a database. I keep getting this error, but I am not sure why.
    Error: "Too few parameters. Expected 1."
    //To delete a row
      public void removeRow(String x, String y) {
       try {
       Statement stmt = con.createStatement();
       //delete row with same x and y
    //first is a string and second is a number
       String query = "DELETE * FROM table WHERE first = '" +x+ "' AND " +
       "second = " +Integer.parseInt(y);
       int result = stmt.executeUpdate(query); //runs delete query, ERROR HERE *************
       System.out.println("Test"); //debug statement, never gets here
       //deletion confirmation message
       JOptionPane.showMessageDialog(null, "Row deleted",
       "Delete Reservation", JOptionPane.INFORMATION_MESSAGE);
          catch (Exception e) { System.out.println(e); }

    Additionally, in the future you might want to use:
    catch(SQLException sqlx) {
      System.out.println( sqlx.getSQLState()
                                       +"\t"+sqlx.getMessage()
                                       +"\t"+sqlx.getErrorCode() );... It'll help with diagnostics.
    &#9786;Bill

  • Deleting a row from a table using jsp

    Given a table in a jsp, can an user click on a row of that table and retrieve the information so that the program can delete a record from a database table?
    most of the tables that I have seen are static, the user cannot interact with them(specially when the user wants to delete several records from a database table).
    Can anyone suggests a good book or way of deleting a row from table using jsp.

    eg use a column in the table that has a radio button or check box,
    on submit, get all the rows that are checked, using the row as an index into your db store, get the key and use the key to issue the sql delete command.

  • Deleting a row from parent table

    Dear Guru's
    I am having two table with parent - child relationship. My problem is when I am deleting a row from parent table the curresponding child row from child table also should be deleted.
    My Primary table 'Employee, EMPID Primary key
    Child table 'Privilage' inthis EMPID referencing the EMPID of Employee table
    My need is when I am deleting a row from parent table the curresponding child row from child table also should be deleted
    I issued the SQL query like,
    delete from employee where empid='12345' cascade constraints;
    Then it showing me error like,
    ERROR at line 1:
    ORA-00933: SQL command not properly ended
    Please resolve my issue , Its Top urgent
    Thanks & Cheers
    Antony

    Choosing How Foreign Keys Enforce Referential Integrity
    Oracle Database allows different types of referential integrity actions to be enforced, as specified with the definition of a FOREIGN KEY constraint:
    Prevent Delete or Update of Parent Key The default setting prevents the deletion or update of a parent key if there is a row in the child table that references the key. For example:
    CREATE TABLE Emp_tab ( 
    FOREIGN KEY (Deptno) REFERENCES Dept_tab);Delete Child Rows When Parent Key Deleted The ON DELETE CASCADE action allows parent key data that is referenced from the child table to be deleted, but not updated. When data in the parent key is deleted, all rows in the child table that depend on the deleted parent key values are also deleted. To specify this referential action, include the ON DELETE CASCADE option in the definition of the FOREIGN KEY constraint. For example:
    CREATE TABLE Emp_tab (
        FOREIGN KEY (Deptno) REFERENCES Dept_tab 
            ON DELETE CASCADE); Set Foreign Keys to Null When Parent Key Deleted The ON DELETE SET NULL action allows data that references the parent key to be deleted, but not updated. When referenced data in the parent key is deleted, all rows in the child table that depend on those parent key values have their foreign keys set to null. To specify this referential action, include the ON DELETE SET NULL option in the definition of the FOREIGN KEY constraint. For example:
    CREATE TABLE Emp_tab (
        FOREIGN KEY (Deptno) REFERENCES Dept_tab 
            ON DELETE SET NULL);
    SQL> conn scott/tiger
    Connected.
    SQL> create table ppk ( no number primary key);
    Table created.
    SQL> begin for inn in 1..10 loop insert into ppk values (inn); end loop; end;
    PL/SQL procedure successfully completed.
    SQL> create table ffk ( no number references ppk(no));
    Table created.
    SQL> begin for inn in 1..10 loop insert into ffk values (inn); end loop; end;
    PL/SQL procedure successfully completed.
    SQL> drop table ppk cascade constraints;
    Table dropped.Message was edited by:
    user52
    Message was edited by:
    user52
    Message was edited by:
    user52

Maybe you are looking for