Ошибка заданное приведение является недопустимым

murai

0 / 0 / 0

Регистрация: 10.10.2019

Сообщений: 17

1

.NET 5

18.12.2020, 22:40. Показов 2334. Ответов 1

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Нажимаю на строчку в таблице — выдает эту ошибку (System.InvalidCastException: «Заданное приведение является недопустимым.»).
ошибка в строчке id = (int?)dataGridView1[0, dataGridView1.SelectedRows[0].Index].Value;
В чем может быть проблема? Датагрид настроен верно, в других формах ошибку не выдает, настроены одинаково

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace CompSecurity
{
    public partial class Workers : Form
    {     
       int? id;
 
        void LoadData(Context db)
        {
            dataGridView1.DataSource = db.Workers.ToList();
            Clear();
        }
 
        void Clear()
        {
            dataGridView1.ClearSelection();
            id = null;
            txtBoxWorkerFIO.Text = txtBoxWorkerSalary.Text = txtBoxWorkerCitizenship.Text
            = txtBoxWorkerDateOfBirth.Text = txtBoxWorkerAddress.Text = txtBoxPhone.Text = "";
        }
 
        bool CheckData()
        {
            return txtBoxWorkerFIO.Text != "" && txtBoxWorkerSalary.Text != "" && txtBoxWorkerCitizenship.Text != ""
            && txtBoxWorkerDateOfBirth.Text != "" && txtBoxWorkerAddress.Text != "" && txtBoxPhone.Text != "";
        }
 
        Worker FindWorkers(Context db)
        {
        return db.Workers.Where(s => s.WorkerId == id).First();
        }
  
        public Workers()
        {
            InitializeComponent();
        }
        private void Workers_Load_1(object sender, EventArgs e)
        {
            using (Context db = new Context())
            {
                LoadData(db);
            }
        }
         private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
           {
            id = (int?)dataGridView1[0, dataGridView1.SelectedRows[0].Index].Value;
 
            using (Context db = new Context())
            {
                Worker worker = FindWorkers(db);
 
                txtBoxWorkerFIO.Text = worker.FIO;
                txtBoxWorkerSalary.Text = worker.Salary;
                txtBoxWorkerCitizenship.Text = worker.Citizenship;
                txtBoxWorkerDateOfBirth.Text = worker.DateOfBirth;
                txtBoxWorkerAddress.Text = worker.Address;
                txtBoxPhone.Text = worker.PhoneNumber;
            }
 
        }
        private void BtnInsert_Click(object sender, EventArgs e)
        {
              if (!CheckData())
                 MessageBox.Show("Введите данные");
             else
             using (Context db = new Context())
             {
                 db.Workers.Add(
                 new Worker
                 {
                    FIO = txtBoxWorkerFIO.Text,
                    Salary = txtBoxWorkerSalary.Text,
                    Citizenship = txtBoxWorkerCitizenship.Text,
                    DateOfBirth = txtBoxWorkerDateOfBirth.Text,
                    Address = txtBoxWorkerAddress.Text,
                    PhoneNumber = txtBoxPhone.Text
                 });
                db.SaveChanges();
                LoadData(db);
             }
             Clear();
        }
 
        private void BtnUpdate_Click(object sender, EventArgs e)
        {
 
        }
 
        private void BtnDelete_Click(object sender, EventArgs e)
        {
            using (Context db = new Context())
            {
                Worker worker = FindWorkers(db);
 
                if (MessageBox.Show($"Вы уверены, что хотите удалить работника {worker.FIO}?n", "Подтверждение удаления",
                            MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (worker.Services.Count > 0)
                    {
                        var service = db.Services.Where(s => s.WorkerId == id);
 
                        foreach (Service s in service)
                        {
                            db.Services.Remove(s);
                        }
                        MessageBox.Show("Также будет удалена запись о предоставлении услуг");
                    }
                    db.Workers.Remove(worker);
 
                    db.SaveChanges();
                    LoadData(db);
                }
                else Clear();
            }
        }
 
       
    }
}



0



HF

979 / 645 / 161

Регистрация: 09.09.2011

Сообщений: 1,961

Записей в блоге: 2

19.12.2020, 10:02

2

Лучший ответ Сообщение было отмечено murai как решение

Решение

Цитата
Сообщение от murai
Посмотреть сообщение

В чем может быть проблема?

Если он прямым текстом говорит что это приведение недопустимо.
Дело наверное в том что «int?» не тот тип для явного значения ячейки.

Цитата
Сообщение от murai
Посмотреть сообщение

C#
1
2
3
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
id = (int?)dataGridView1[0, dataGridView1.SelectedRows[0].Index].Value;

Так же рекомендую перестать так писать и воспользоваться тем что явно предоставляется в реализации. Событие для того и создано чтобы реагировать на нужное действие и сообщать об этом в параметрах. Я к тому что sender — это и есть DataGridView, а в «e» находятся нужная информация по ячейке которую собственно кликнули. И тогда не нужно никаких индексов и поисков.



1



Note: I am looking for why this is happening and how to fix it, I am not looking for a workaround. This appears to be a server(SQL Server or Connection string) issue.

I have a program that is connected to a sql 2008 database (Database A) and I have inline sql that runs that has ints and strings returned and it works fine. But I have been asked to switch to another 2008 database (Database B) and now everything is coming back as a string and I am getting a specified cast is not valid from C# where when I am connected to the sql 2008 (Database A) it does not say this. This is a inline sql statement so the sql statement is not changing and the table schema of the database is the same. Its doing this on int primary keys Anyone have any ideas?

I originally thought the was a 2000 to 2008 issue but I now have the some problem on 2008 as well. Both databases are on the same instance of sql server these are the connection strings

Connection Strings

  Server=Server01instance;Database=Fraud_Micah; Trusted_Connection=yes <- Server 2008 (this one does not)
  Server=Server02instance;Database=Fraud; Trusted_Connection=yes <- Server 2008 (this one works)

Both databases are at DB compatibility_level of 100

The select Statement

select *, delimeter, file_filetype.LocalPath, ArchiveDir, EmailList
from file_importtable 
join file_filetype on file_importtable.FileTypeID = file_filetype.ID
where importsuccessdate is null and transferdate is not null
and remotediscoverdate is not null 
and OriginalFileName in ('Test987.xml.pgp')

fileTypeID is where its breaking -> InvalidCastException: Specified cast is not valid.

C# Code (Note reader is type SQLDataReader)

if (!(reader.IsDBNull(reader.GetOrdinal("FileTypeID"))))
{
    file.FileTypeID = reader.GetInt32(reader.GetOrdinal("FileTypeID"));
}

Here is the column definition: [FileTypeID] [int] NULL, there is no null values in the table.

I don’t think the C# code comes from this, its a int? public int? FileTypeID { get; set; }

In debug mode: reader["FileTypeID"] -> «1» it is in fact a string but why when I connect to a 2008 database would it return a 1 instaed of a «1»

2008 Table A Def

[ProcessSuccessDate] [datetime] NULL,
[ProcessSuccessUser] [datetime] NULL,
[FileTypeID] [int] NULL,
[HoldDate] [datetime] NULL,

2008 Table B Def

ProcessSuccessDate] [datetime] NULL,
[ProcessSuccessUser] [datetime] NULL,
[FileTypeID] [int] NULL,
[HoldDate] [datetime] NULL,

file.FileTypeID = (int)reader["FileTypeID"]; yields the same result.

Doing a

     file.FileTypeID (int)reader.GetInt32(reader.GetOrdinal("FileTypeID"));

does work but I don’t want to do that for every column that already should be coming back as a int also writing sql like this

     select Convert(int, FileTypeID) as FileTypeId, delimeter, file_filetype.LocalPath, ArchiveDir, EmailList

can get around the issue as well, however I want to know why I have to do this if I already set the type as a int in the table. I might as well put all the types as strings in the table. At this point I am not looking for a workaround I want to understand why its not working like it should be.

Нужна помощь. Есть база данных в microsoft sql server. Я хочу чтоб таблица отобразилась на windows форме с помощью datagridview. Но при запуске появляется ошибка (в заголовке).

public partial class Form1 : Form
{
    DataBase dataBase = new DataBase();
    public Form1()
    {
        InitializeComponent();

    }

    private void CreateColumns()
    {
        dataGridView1.Columns.Add("adr_id", "id");
        dataGridView1.Columns.Add("name", "Iм'я");
        dataGridView1.Columns.Add("bday", "День народження");
        dataGridView1.Columns.Add("address", "Адреса");
        dataGridView1.Columns.Add("tel", "Телефон");
        dataGridView1.Columns.Add("IsNew", String.Empty);
    }

    private void ReadSingleRow(DataGridView dgw, IDataRecord record)
    {
        dgw.Rows.Add(record.GetInt32(0), record.GetString(1), record.GetDateTime(2), record.GetString(3), record.GetInt32(4), RowState.ModifiedNew);
    }

    private void RefreshDataGrid(DataGridView dgw)
    {
        dgw.Rows.Clear();
        string queryString = $"select * from addressee";
        SqlCommand command = new SqlCommand(queryString, dataBase.GetConnection());
        dataBase.openConnection();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            ReadSingleRow(dgw, reader);
        }
        reader.Close();

    }

    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void label2_Click(object sender, EventArgs e)
    {

    }

    private void label_bday_Click(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CreateColumns();
        RefreshDataGrid(dataGridView1);
    }
}

debug

debug

debug

Jenya2802

0 / 0 / 0

Регистрация: 19.11.2018

Сообщений: 42

1

14.12.2018, 16:39. Показов 23224. Ответов 7

Метки нет (Все метки)


C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
 
namespace PersonLibrary
{
    public class PersonList : List<PersonInfo>
    {
        public static PersonList GetDefaultPersonList()
        {
            PersonList myList = new PersonList();
 
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = "Data Source=PCSQLEXPRESS; Initial Catalog=PersonDB; Integrated Security=True";
            cn.Open();
 
            SqlCommand cm = cn.CreateCommand();
            cm.CommandType = CommandType.StoredProcedure;
            cm.CommandText = "GetPersonList";
           
 
 
            SqlDataReader dr = cm.ExecuteReader();
 
            while (dr.Read())
            {
                PersonInfo newPerson = new PersonInfo();
                newPerson.PersonFirstName = dr["PersonFirstName"].ToString();
                newPerson.PersonSecondName = dr["PersonSecondName"].ToString();
                newPerson.PersonDateBirth = (DateTime)dr["PersonDateBirth"];
                newPerson.PersonAddress = dr["PersonAddress"].ToString();
                newPerson.PersonID = (int)dr["PersonID"];
                newPerson.SpecialityID = (int)dr["SpecialityID"];
                newPerson.SpecialityName = dr["SpecialityName"].ToString();
 
                myList.Add(newPerson);
           
 
            }
 
 
            return myList;
        }
    }
 
 
}

Вот код класса в котором возникает ошибка. Данные из БД не загружаются, и появляется вот это. Хотя в БД везде стоит int, в процедурах тоже, в чем может быть ошибка? Ошибка в этой строке «newPerson.SpecialityID = (int)dr[«SpecialityID»];»

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Администратор

Эксперт .NET

15226 / 12265 / 4902

Регистрация: 17.03.2014

Сообщений: 24,867

Записей в блоге: 1

14.12.2018, 17:15

2

Jenya2802, значит все-таки не int, раз исключение возникает. Посмотри через отладчик настоящий тип значения.

0

0 / 0 / 0

Регистрация: 19.11.2018

Сообщений: 42

14.12.2018, 17:24

 [ТС]

3

А как в отладчике посмотреть тип значения? Я просто только начала c# изучать, не совсем понимаю..

0

0 / 0 / 0

Регистрация: 19.11.2018

Сообщений: 42

14.12.2018, 17:25

 [ТС]

4

Если так, то здесь int, но он почему-то возвращает 0

Миниатюры

System.InvalidCastException: "Заданное приведение является недопустимым."
 

0

783 / 615 / 272

Регистрация: 04.08.2015

Сообщений: 1,707

14.12.2018, 19:06

5

Jenya2802, надо смотреть dr[«SpecialityID»]. Там или null или строка.

0

OwenGlendower

Администратор

Эксперт .NET

15226 / 12265 / 4902

Регистрация: 17.03.2014

Сообщений: 24,867

Записей в блоге: 1

14.12.2018, 20:24

6

Лучший ответ Сообщение было отмечено Jenya2802 как решение

Решение

Цитата
Сообщение от Jenya2802
Посмотреть сообщение

Если так

Не так. Смотреть нужно что возвращает dr["SpecialityID"].

Цитата
Сообщение от Igr_ok
Посмотреть сообщение

Там или null или строка

Скорее null. Jenya2802, попробуй так переписать:

C#
1
newPerson.SpecialityID = dr["SpecialityID"] == DBNull.Value ? null : (int?)dr["SpecialityID"];

Тип свойства SpecialityID нужно изменить на int?

2

0 / 0 / 0

Регистрация: 19.11.2018

Сообщений: 42

15.12.2018, 15:30

 [ТС]

7

А с этим что делать?

Миниатюры

System.InvalidCastException: "Заданное приведение является недопустимым."
 

0

Администратор

Эксперт .NET

15226 / 12265 / 4902

Регистрация: 17.03.2014

Сообщений: 24,867

Записей в блоге: 1

16.12.2018, 00:24

8

Цитата
Сообщение от Jenya2802
Посмотреть сообщение

А с этим что делать?

Выше уже ответил:

Цитата
Сообщение от OwenGlendower
Посмотреть сообщение

Тип свойства SpecialityID нужно изменить на int?

1

I have a backup from database in SQL Server 2008 R2.
When I want to restore this backup to SQL Server, I get this error:
«Error: Specified cast is not valid. (SqlManagerUI)»
How to I resolve this error?
Thanks.

asked Apr 10, 2012 at 11:22

Tavousi's user avatar

1

This would also happen when you are trying to restore a newer version backup in a older SQL database. For example when you try to restore a DB backup that is created in 2012 with 110 compatibility and you are trying to restore it in 2008 R2.

answered Jul 29, 2013 at 5:58

user1089020's user avatar

user1089020user1089020

1732 silver badges4 bronze badges

1

There are some funnies restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?

Use Master
Go
RESTORE DATABASE YourDB
FROM DISK = 'C:YourBackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:DataYourMDFFile.mdf',--check and adjust path
MOVE 'YourLDFLogicalName' TO 'D:DataYourLDFFile.ldf' 

Community's user avatar

answered Apr 12, 2012 at 14:21

u07ch's user avatar

u07chu07ch

13.1k5 gold badges42 silver badges47 bronze badges

2

Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?

RESTORE VERIFYONLY FROM DISK = N'd:yourbackup.bak'

if it gives error like:

Msg 3241, Level 16, State 13, Line 2
The media family on device ‘d:alibaba.bak’ is incorrectly formed. SQL Server cannot process this media family.
Msg 3013, Level 16, State 1, Line 2
VERIFY DATABASE is terminating abnormally.

Check it further:

RESTORE HEADERONLY FROM DISK = N'd:yourbackup.bak'

BackupName is «* INCOMPLETE *«,
Position is «1»,
other fields are «NULL».

Means either your backup is corrupt or taken from newer version.

answered Oct 25, 2014 at 1:13

Ali Adravi's user avatar

Ali AdraviAli Adravi

21k9 gold badges83 silver badges83 bronze badges

I had a similar error «Specified cast is not valid» restoring from SQL Server 2012 to SQL Server 2008 R2

First I got the MDF and LDF Names:

RESTORE FILELISTONLY 
FROM  DISK = N'C:Usersdell laptopDotNetSandBoxDBBackupsDavincis3.bak' 
GO

Second I restored with a MOVE using those names returned:

RESTORE DATABASE Davincis3 
FROM DISK = 'C:Usersdell laptopDotNetSandBoxDBBackupsDavincis3.bak'
WITH 
   MOVE 'JQueryExampleDb' TO 'C:Program FilesMicrosoft SQL ServerMSSQL10_50.MSSQLSERVERMSSQLDATADavincis3.mdf', 
   MOVE 'JQueryExampleDB_log' TO 'C:Program FilesMicrosoft SQL ServerMSSQL10_50.MSSQLSERVERMSSQLDATADavincis3.ldf', 
REPLACE
GO  

I have no clue as to the name «JQueryExampleDb», but this worked for me.

Nevertheless, backups (and databases) are not backwards compatible with older versions.

answered Dec 8, 2014 at 0:04

Paul's user avatar

PaulPaul

9642 gold badges13 silver badges37 bronze badges

I have a backup from database in SQL Server 2008 R2.
When I want to restore this backup to SQL Server, I get this error:
«Error: Specified cast is not valid. (SqlManagerUI)»
How to I resolve this error?
Thanks.

asked Apr 10, 2012 at 11:22

Tavousi's user avatar

1

This would also happen when you are trying to restore a newer version backup in a older SQL database. For example when you try to restore a DB backup that is created in 2012 with 110 compatibility and you are trying to restore it in 2008 R2.

answered Jul 29, 2013 at 5:58

user1089020's user avatar

user1089020user1089020

1732 silver badges4 bronze badges

1

There are some funnies restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?

Use Master
Go
RESTORE DATABASE YourDB
FROM DISK = 'C:YourBackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:DataYourMDFFile.mdf',--check and adjust path
MOVE 'YourLDFLogicalName' TO 'D:DataYourLDFFile.ldf' 

Community's user avatar

answered Apr 12, 2012 at 14:21

u07ch's user avatar

u07chu07ch

13.1k5 gold badges42 silver badges47 bronze badges

2

Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?

RESTORE VERIFYONLY FROM DISK = N'd:yourbackup.bak'

if it gives error like:

Msg 3241, Level 16, State 13, Line 2
The media family on device ‘d:alibaba.bak’ is incorrectly formed. SQL Server cannot process this media family.
Msg 3013, Level 16, State 1, Line 2
VERIFY DATABASE is terminating abnormally.

Check it further:

RESTORE HEADERONLY FROM DISK = N'd:yourbackup.bak'

BackupName is «* INCOMPLETE *«,
Position is «1»,
other fields are «NULL».

Means either your backup is corrupt or taken from newer version.

answered Oct 25, 2014 at 1:13

Ali Adravi's user avatar

Ali AdraviAli Adravi

21k9 gold badges83 silver badges83 bronze badges

I had a similar error «Specified cast is not valid» restoring from SQL Server 2012 to SQL Server 2008 R2

First I got the MDF and LDF Names:

RESTORE FILELISTONLY 
FROM  DISK = N'C:Usersdell laptopDotNetSandBoxDBBackupsDavincis3.bak' 
GO

Second I restored with a MOVE using those names returned:

RESTORE DATABASE Davincis3 
FROM DISK = 'C:Usersdell laptopDotNetSandBoxDBBackupsDavincis3.bak'
WITH 
   MOVE 'JQueryExampleDb' TO 'C:Program FilesMicrosoft SQL ServerMSSQL10_50.MSSQLSERVERMSSQLDATADavincis3.mdf', 
   MOVE 'JQueryExampleDB_log' TO 'C:Program FilesMicrosoft SQL ServerMSSQL10_50.MSSQLSERVERMSSQLDATADavincis3.ldf', 
REPLACE
GO  

I have no clue as to the name «JQueryExampleDb», but this worked for me.

Nevertheless, backups (and databases) are not backwards compatible with older versions.

answered Dec 8, 2014 at 0:04

Paul's user avatar

PaulPaul

9642 gold badges13 silver badges37 bronze badges

Перейти к содержимому раздела

Форумы CADUser

Информационный портал для профессионалов в области САПР

Вы не вошли. Пожалуйста, войдите или зарегистрируйтесь.

Дерево сообщений Активные темы Темы без ответов

Ошибка приведения

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

#1 10 октября 2012г. 11:27:27

  • andr1990
  • Участник
  • На форуме с 8 августа 2012г.
  • Сообщений: 50
  • Спасибо: 1

Тема: Ошибка приведения

Вылетает ошибка: Заданное приведение является недопустимым

AcadMText MTextObj = null;

MTextObj = ((AcadDocument)Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.

AcadDocument).PaperSpace.AddMText(TPoints, Width, st);

При наведении на ####.PaperSpace.##### отображается «Заданное приведение является недопустимым»

Хотя условие обрабатывается корректно

if (((AcadDocument)Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.

AcadDocument).ActiveSpace == Autodesk.AutoCAD.Interop.Common.AcActiveSpace.acModelSpace)

переходит на else, показывает что ActiveSpace == PaperSpace. Как исправить?

#2 Ответ от Modis 10 октября 2012г. 20:33:27

  • Modis
  • Modis
  • Активный участник
  • Откуда: Липецк
  • На форуме с 17 февраля 2008г.
  • Сообщений: 892
  • Спасибо: 14

Re: Ошибка приведения

Вообще-то примитивы надо добавлять используя транзакцию…

#3 Ответ от Modis 10 октября 2012г. 20:39:20

  • Modis
  • Modis
  • Активный участник
  • Откуда: Липецк
  • На форуме с 17 февраля 2008г.
  • Сообщений: 892
  • Спасибо: 14

Re: Ошибка приведения

Вот тебе пример. Где поменять ModelSpace на PaperSpace думаю не сложно догадаться :)

#4 Ответ от andr1990 11 октября 2012г. 12:13:34

  • andr1990
  • Участник
  • На форуме с 8 августа 2012г.
  • Сообщений: 50
  • Спасибо: 1

Re: Ошибка приведения

У меня весь проект на COM, не хочется всё менять на .NET …

#5 Ответ от Modis 11 октября 2012г. 13:15:16

  • Modis
  • Modis
  • Активный участник
  • Откуда: Липецк
  • На форуме с 17 февраля 2008г.
  • Сообщений: 892
  • Спасибо: 14

Re: Ошибка приведения

Андрей Третьяк пишет:

У меня весь проект на COM, не хочется всё менять на .NET …

Оу… Тогда все вопросы к Ривилису :)

#6 Ответ от fixo 11 октября 2012г. 17:47:35

  • fixo
  • fixo
  • Активный участник
  • Откуда: СПб
  • На форуме с 7 февраля 2009г.
  • Сообщений: 869
  • Спасибо: 41

Re: Ошибка приведения

Андрей Третьяк пишет:

MTextObj = ((AcadDocument)Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.
AcadDocument).PaperSpace.AddMText(TPoints, Width, st);

Наверно ругается что ты мтекст пытаешься привести к типу AcadDocument,
попробуй так:

MTextObj = (AcadMText)((AcadDocument)Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument. 
AcadDocument).PaperSpace.AddMText(TPoints, Width, st); 

[FONT=Arial]~’J’~[/FONT]

#7 Ответ от andr1990 12 октября 2012г. 08:26:57 (изменено: Андрей Третьяк, 12 октября 2012г. 08:29:19)

  • andr1990
  • Участник
  • На форуме с 8 августа 2012г.
  • Сообщений: 50
  • Спасибо: 1

Re: Ошибка приведения

Нет, он ругается при наведении на PaperSpace. Ошибка: AcadCurrentInstances.ThisDrawing.PaperSpace = ‘AcadCurrentInstances.ThisDrawing.PaperSpace’ threw an exception of type ‘System.InvalidCastException’. Вообще стркока в коде выглядит вот так:

MTextObj = AcadCurrentInstances.ThisDrawing.PaperSpace.AddMText(TPoints, Width, st);

где

ThisDrawing = (AcadDocument)Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.AcadDocument;

(я думаю это ничего не изменило; использовал первый вариант для наглядности).
При выполнении идёт переключение между layout’ами, возможно ошибка в переключении (при переключении с непервого на первый).
Переключаюсь так

AcadCurrentInstances.ThisDrawing.ActiveLayout = Layout;

где AcadCurrentInstances:

public class AcadCurrentInstances
    {
        public static AcadDocument ThisDrawing
        {
            get { return (AcadDocument)Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.AcadDocument; }
        }

        public static AcadApplication AcadApplication
        {
            get { return (AcadApplication)Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication; }
        }

        
    }

#8 Ответ от fixo 12 октября 2012г. 08:32:38

  • fixo
  • fixo
  • Активный участник
  • Откуда: СПб
  • На форуме с 7 февраля 2009г.
  • Сообщений: 869
  • Спасибо: 41

Re: Ошибка приведения

У меня было что-то похожее при работе с лэйаутами,

попробуй при переходе на другой лист сначала перейти в Модель,

а потом на конкретный лист, нет времени тестировать

#9 Ответ от andr1990 12 октября 2012г. 09:04:01

  • andr1990
  • Участник
  • На форуме с 8 августа 2012г.
  • Сообщений: 50
  • Спасибо: 1

Re: Ошибка приведения

Не помогает

#10 Ответ от andr1990 19 октября 2012г. 13:15:23 (изменено: Андрей Третьяк, 19 октября 2012г. 13:16:23)

  • andr1990
  • Участник
  • На форуме с 8 августа 2012г.
  • Сообщений: 50
  • Спасибо: 1

Re: Ошибка приведения

При возникновении ошибки «Заданное приведение является недопустимым» у объекта ThisDrawing (тип AcadDocument) переменная
ModelSpace = {System.__ComObject}
а переменная
PaperSpace = {System.Reflection.TargetInvocationException: Адресат вызова создал исключение. —> System.InvalidCastException: Интерфейс не поддерживается (Исключение из HRESULT: 0x80004002 (E_NOINTERFACE))
   — Конец трассировки внутреннего стека исключений —
   в System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
   в System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   в System.Dynamic.IDispatchComObject.GetMembers(IEnumerable`1 names)}

Почему возникает такая ошибка?

#11 Ответ от andr1990 22 октября 2012г. 08:22:31

  • andr1990
  • Участник
  • На форуме с 8 августа 2012г.
  • Сообщений: 50
  • Спасибо: 1

Re: Ошибка приведения

Нашёл интересную статью
http://forums.autodesk.com/t5/Visual-Ba … rue#M88351. Но понять суть решения так и не смог. Помогите разобраться.
Norman Yuan пишет: So, you must only add test (or other entities) to PaperSpace when the layout
is NOT «Model». Если это значит, что можно добавить entity когда текущий layout не «Модель», но в этом же и заключается суть проблемы

#12 Ответ от andr1990 22 октября 2012г. 08:38:16 (изменено: Андрей Третьяк, 22 октября 2012г. 12:36:37)

  • andr1990
  • Участник
  • На форуме с 8 августа 2012г.
  • Сообщений: 50
  • Спасибо: 1

Re: Ошибка приведения

На Layote, который был активным перед вызовом цикла эта ошибка не вылетает

 foreach (AcadLayout Layout in AcadCurrentInstances.ThisDrawing.Layouts)
            {
                if (Layout.Name != "Model")
                {
                    AcadCurrentInstances.ThisDrawing.ActiveLayout = Layout;                    
                    ............
                    ............
                }
            }

Подскажите, какие переменные меняются при переходе на другой Layout?

#13 Ответ от andr1990 2 ноября 2012г. 06:53:55 (изменено: Андрей Третьяк, 2 ноября 2012г. 06:55:28)

  • andr1990
  • Участник
  • На форуме с 8 августа 2012г.
  • Сообщений: 50
  • Спасибо: 1

Re: Ошибка приведения

Решил проблему заменой

Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication.ActiveDocument.PaperSpace

на

Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication.ActiveDocument.ActiveLayout.Block

Сообщения 13

Тему читают: 1 гость

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

  • Remove From My Forums
  • Question

  • My environment is:

    Operating System: Windows 7 Pro (32bit), Finnish

    I use Virtual PC including in Windows 7

    Operating system in Virtual PC: Windows Server 2008 Standard.

    SQL Sever 2008 R2

    Under SQL Server Management Studio,

    I have a database backup file created by different user in same environment (Virtual PC + Windows Server2008 + SQL Server 2008 R2)

    When I try to restore a Database from backup file I get following message:

    TITLE: Microsoft SQL Server Management Studio
    ——————————

    Specified cast is not valid. (SqlManagerUI)

    ——————————
    BUTTONS:

    OK
    ——————————

    What I made wrong ?

    • Moved by

      Tuesday, June 1, 2010 4:20 PM
      Backup/restore problem (From:SQL Server Integration Services)

Answers

  • Do «RESTORE FILELISTONLY FROM DISK = N’E:ERPDW_31052010.bak’»  and adjust your RESTORE command’s MOVE options to match the files as indicated, so that the RESTORE command can create those files for you.


    Tibor Karaszi, SQL Server MVP | http://www.karaszi.com/sqlserver/default.asp | http://sqlblog.com/blogs/tibor_karaszi

    • Marked as answer by
      Alex Feng (SQL)
      Tuesday, June 8, 2010 11:25 AM
  • Remove From My Forums
  • Question

  • My environment is:

    Operating System: Windows 7 Pro (32bit), Finnish

    I use Virtual PC including in Windows 7

    Operating system in Virtual PC: Windows Server 2008 Standard.

    SQL Sever 2008 R2

    Under SQL Server Management Studio,

    I have a database backup file created by different user in same environment (Virtual PC + Windows Server2008 + SQL Server 2008 R2)

    When I try to restore a Database from backup file I get following message:

    TITLE: Microsoft SQL Server Management Studio
    ——————————

    Specified cast is not valid. (SqlManagerUI)

    ——————————
    BUTTONS:

    OK
    ——————————

    What I made wrong ?

    • Moved by

      Tuesday, June 1, 2010 4:20 PM
      Backup/restore problem (From:SQL Server Integration Services)

Answers

  • Do «RESTORE FILELISTONLY FROM DISK = N’E:ERPDW_31052010.bak’»  and adjust your RESTORE command’s MOVE options to match the files as indicated, so that the RESTORE command can create those files for you.


    Tibor Karaszi, SQL Server MVP | http://www.karaszi.com/sqlserver/default.asp | http://sqlblog.com/blogs/tibor_karaszi

    • Marked as answer by
      Alex Feng (SQL)
      Tuesday, June 8, 2010 11:25 AM
  • Remove From My Forums
  • Вопрос

  • Здравствуйте.

    Имеется ОС Windows Server 2008 R2 Enterprice (RUS), установлен MSSQL 2012 Enterprice (RUS) и MSSQL 2008 R2 Enterprice (RUS).

    Делаю backup БД средствами «SQL Server Management Studio» MSSQL 2012, получаю bak файл.

    Из этого  bak файла опять же  средствами «SQL Server Management Studio» MSSQL 2012 могу успешно восстановить БД.

    Но при восстановлении БД  средствами «SQL Server Management Studio» MSSQL 2008 происходит ошибка «Заданное приведение является недопустимым. (SqlManagerUI)» в момент выбора файла BackUP`а.

    Подскажите как БД с MSSQL 2012 корректно развернуть на MSSQL 2008 R2

Ответы

  • Если я правильно понял, вы пытаетесь восстановить бэкап базы sql 2012, в sql 2008 — это сделать невозможно, единственное, что можно попробовать, это использовать функцию Generate Scripts(если она еще есть 2012) и там указать совместимость с 2008r2(опять-таки
    если там есть такая опция)

    • Помечено в качестве ответа

      15 января 2013 г. 9:54

  • Но при восстановлении БД  средствами «SQL Server Management Studio» MSSQL 2008 происходит ошибка «Заданное приведение является недопустимым. (SqlManagerUI)» в момент выбора файла BackUP`а.

    Подскажите как БД с MSSQL 2012 корректно развернуть на MSSQL 2008 R2

    Средствами SQL — никак. Резервные копии сделанные в более поздних версиях MS SQL Server нельзя восстанавливать в более ранних.

    Если база 1С, то можешь это сделать 1Сными средствами — выгрузить ее в конфигураторе из 2012го и загрузить там же в 2008йR2 (для больших баз — очень долгая процедура)


    Andy Mishechkin

    • Помечено в качестве ответа
      Roman Zhukov
      15 января 2013 г. 9:54

Здравствуйте. Создал класс представляющий таблицу в SQL —  tbl_Invoce

// Накладная
    [Table(Name= "tbl_Invoce")]
    public class CInvoce 
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)] 
        // Номер документа
        public int DocumentId { set; get; } // 

        // Товар
        [Column]
        public string MaterialId{ set; get; }

        // Количество
        [Column]
        public int Quantity{ set; get; }

        // Цена
        [Column]
        public decimal Price{ set; get; }

        // Дата 
        [Column]
        public DateTime Date{ set; get; }

        // Ответственный 
        [Column]
        public string Accountable{ set; get; }


         private EntityRef<CMaterial> m;// = new EntityRef<CMaterial>();
        [Association(Storage = "m", ThisKey="MaterialId", OtherKey = "ID")]
        public CMaterial M
        {
            get {return m.Entity ;}
            set { m.Entity = value;}
        } // список накладных List<CInvoce> invoce = new List<CInvoce>(); // Добавление накладной public void AddInvoce(CInvoce invoce) { // CMaterial material = } }

Необходимо заполнить datagridView значениями  из этой таблицы. Вот  метод реализующий необходимое:

private void RefreshGridViewInvoce()
        {
//1)
             //List<CInvoce> invoces = dc.GetTable<CInvoce>().ToList();
            //dgvColInvoce.DataSource = invoces;

//2)
           Table<CInvoce> table= dc.GetTable<CInvoce>();
            dgvColInvoce.DataSource = table;
        }

Как первым, так и вторым способом выводиться ошибка InvalidCastException «Заданное приведение является недопустимым.»

Скажите, пожалуйста, в чем причина ошибки и как нужно исправить код.

Вот проект таблицы в SQL-сервере

Design

  • Ошибка загрузки файлов http failure response for unknown url 0 unknown error егиссо
  • Ошибка задан неизвестный параметр командной строки dynamic update
  • Ошибка загрузки файла что делать
  • Ошибка загрузочный диск не обнаружен или произошел сбой диска
  • Ошибка загрузки файла сортировки базы данных 1cv7 ord