LoadDataRow Specified Cast Error

A

Assimalyst

Hi,

I'm attempting to copy the priamry key from table "Surgeon" to be a
foreign key in "Assessment" within a dataset.

here is the data to add to the surgeon table:

if(addNewSurgeonChkBx.Checked == true)
{
DataRow surgeonRow = dsAddAssessment.Tables["Surgeon"].NewRow();
surgeonRow["sgnTitle"] = titleCboBx.SelectedValue;
surgeonRow["sgnFName"] = fNameTxtBx.Text;
surgeonRow["sgnLName"] = lNameTxtBx.Text;
surgeonRow["estNo"] = Session["establishment"].ToString();
dsAddAssessment.Tables["Surgeon"].Rows.Add(surgeonRow);
}

I have similar code for the "Assessment" table.

The PK, sgnNo, is set as an identity in a stored procedure, normally i
can add this to "Assessment" using

assessmentRow.SetParentRow(surgeonRow);

However, surgeon Row is not recognised as Existing in the class or
namespace, due to it being declared in a if statement.

I therefore need a method of declaring it again just before
assessmentRow.SetParentRow(surgeonRow); and loading the the required
row from table "surgeon" in tha dataset.

I have tried this:

if(addNewSurgeonChkBx.Checked == true)
{
// Create an array for the values.
object[] newRow = new object[1];
newRow [0] = dsAddAssessment.Tables["Surgeon"].Rows[0];
dsAddAssessment.Tables["Surgeon"].BeginLoadData();
DataRow surgeonRow =
dsAddAssessment.Tables["Surgeon"].LoadDataRow(newRow, true);
dsAddAssessment.Tables["Surgeon"].EndLoadData();
assessmentRow.SetParentRow(surgeonRow);
}

but get the following error when LoadDataRow is attempted:

{"System.InvalidCastException: Specified cast is not valid.\r\n at
System.Convert.ToInt32(Object value)\r\n at
System.Data.Common.Int32Storage.Set(Int32 record, Object value)\r\n
at System.Data.DataColumn.set_Item(Int32 record, Object value)Couldn't
store <System.Data.DataRow> in surgeonNo Column. Expected type is
Int32." }

Can anyone explain how to solve this, or an alternative way to achieve
a solution?

Thanks
 
A

amir massourian

Hi,

(regarding to cast exception)

in your below code, you are directly assigning the DataRow to your
object[0]; instead, you should set DataRow's values since in LoadDataRow,
you should pass array of values you want to load.

you can either change following line
newRow [0] = dsAddAssessment.Tables["Surgeon"].Rows[0];
to
newRow = dsAddAssessment.Tables["Surgeon"].Rows[0].ItemArray;
or to
newRow [0] = dsAddAssessment.Tables["Surgeon"].Rows[0][_yourDataColumn];

it should remove the type cast exception

thanks
Amir
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top