none
Getting the index of an Item in a DataRow by its column caption RRS feed

  • Question

  • We know that if we have a DataTable, we can populate it with the code like
    DataTable table; DataRow row = table.NewRow(); row["ColName"] = <value>;

     Here "ColName" is the name given to the particular column while creating it, as:

     DataColumn dc = new DataColumn("ColName");
     dc.Caption = "Column Caption";

    I am trying to create a customised ListView control, where I would like my users to deal with the Column Caption values. I do not want them to deal with two entities - the Column name and Caption as it would be confusing. I can't use the column caption for the name either as Caption can contain spaces in it, and names with spaces won't work in a query string (Please correct me if I'm wrong here ...)

    While creating a DataColumn, if we do not specify a name, a default name is generated by the system.

    e.g. if I do
    DataColumn dc = new DataColumn();
    dc.Caption = "Column Caption";

    then - the system generates a name like "Column1" ... Is there a way that I can retrieve this name from the value of the caption? Is there any way to add data to the DataRow just by knowing the column caption??? (without cycling through the Columns list of the DataTable and individually checking for column names ...)

    Thanks in advance.
    Friday, January 15, 2010 6:29 AM

Answers

  • Hello,

    I don’t think we can verify a DataColumn only through its caption.  The column in a data row can be found by its index or column name.   It seems that we can only cycle through the column list of the DataTable if we want to use the column caption to identity the column. 

    However, I think we can set the Column name and Caption to be the same string value, and it is valid.  I don’t quite catch the point that the meaning of “the spaces cannot work in a query string”, because such sample codes can give us the correct result:

    ==========================================================================
                DataTable dt = new DataTable();

                dt.Columns.Add("New Column", typeof(int));

     

                dt.Rows.Add(1);

     

                MessageBox.Show(dt.Rows[0]["New Column"].ToString());
    ==========================================================================

     

    Best Regards,
    Lingzhi Sun


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Wednesday, January 20, 2010 6:48 AM
    Moderator