0 / 0 / 0
Регистрация: 11.10.2019
Сообщений: 10
1

Word interop Ribbon1.cs и Form1.cs Как передать данные?

28.10.2019, 17:27. Показов 565. Ответов 2

Студворк — интернет-сервис помощи студентам
Всем привет. Проблема такая> Не знаю как передать данные с одной формы на другую.
Я создал форму в Form1.cs Design. В этой форме имеются два Listbox. В Ribbon.cs(Word панель) у меня кнопка. Когда она нажимается то происходит>
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
private void UuendaNimekiri_Click(object sender, RibbonControlEventArgs e)
        {
 
           
          Form1 MallideVorm = new Form1();  //Creating form from Form1
            
            
            MallideVorm.Show(); // Showing form
         
 
            int ConnectionTest = 0; //will try to connect once
            
            ClientContext ctx = new ClientContext("https://Some.some/some");
            //Configure the handler that will add the header.
            ctx.ExecutingWebRequest +=
            new EventHandler<WebRequestEventArgs>(ctx_MixedAuthRequest);
            //Set the Windows credentials.
            ctx.AuthenticationMode = ClientAuthenticationMode.Default;
            ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;
            //Get the web.
            Web w = ctx.Web;
            //Load lists with all properties. 
            List list = ctx.Web.Lists.GetByTitle("Dokumendid");
            try
            {
                ctx.ExecuteQuery();
            }
            catch
            { ConnectionTest = 1; }
            if (ConnectionTest == 0)
            {
                ctx.Load(list);
            ctx.Load(list.RootFolder);
            ctx.Load(list.RootFolder.Folders);
            ctx.Load(list.RootFolder.Files);
              ctx.ExecuteQuery();
            FolderCollection fcol = list.RootFolder.Folders;
            List<string> lstFile = new List<string>();
            foreach (Folder f in fcol)
            {
                if (f.Name == "Test")
                {
                    ctx.Load(f.Folders);
                    ctx.Load(f.Files);
                    ctx.ExecuteQuery();
                        FolderCollection folderCol = f.Folders;
                    FileCollection fileCol = f.Files;
             
                    string str = "";
 
                        foreach (Microsoft.SharePoint.Client.Folder folder in folderCol)
                        {
                            str = folder.Name;
 
                            // File.AppendAllText(@"C:\install\CSharp\tulemus.txt", $"File name is: {str}" + Environment.NewLine); //for testings
 
                            foreach (Form1 frm in System.Windows.Forms.Application.OpenForms)
                            {
                                if (frm.GetType() == typeof(Form1))
                                {
                                    //RibbonDropDownItem ddItem1 = Globals.Factory.GetRibbonFactory().CreateRibbonDropDownItem();
                                    //ddItem1.Label = $"{str}";
 
                                    Form1 frmTemp = (Form1)frm;
                                    //ddList.Items.Add(ddItem1);
                                    MallideVorm.addItemToListBoxFolder(str);
                                }
                            }
                        }
 
                        foreach (Microsoft.SharePoint.Client.File file in fileCol)
                    {
                        str = file.Name;
 
                            // File.AppendAllText(@"C:\install\CSharp\tulemus.txt", $"File name is: {str}" + Environment.NewLine); //for testings
 
                            foreach (Form1 frm in System.Windows.Forms.Application.OpenForms)
                            {
                                if (frm.GetType() == typeof(Form1))
                                {
                                    //RibbonDropDownItem ddItem1 = Globals.Factory.GetRibbonFactory().CreateRibbonDropDownItem();
                                    //ddItem1.Label = $"{str}";
                                   
                                    Form1 frmTemp = (Form1)frm;
                                    //ddList.Items.Add(ddItem1);
                                   MallideVorm.addItemToListBoxFiles(file.Name);
                                    
                                }
                            }
                    }
                    }
                    
                }
                
            }else { Interaction.MsgBox(" Ei saa ühendust lehega https://kontor.rik.ee/prok/ \n Kas oled võrgus? Proovi kas saad Chrome-is lehele ligi.",MsgBoxStyle.Critical); }
        
        }
Создается новая форма и в ListBoxы записываются данные.
Затем я хочу использовать эти данные в Form1.cs. Там код такой>
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
private void FormFilesBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            //_______________________________________________________Sharepoindist faili alla laadimine ja sealt avamine________________________________________
           
            string selectedFile = FormFilesBox.SelectedItem.ToString();
            
            File.AppendAllText(@"C:\install\CSharp\tulemus.txt", $"File name is: {selectedFile}" + Environment.NewLine);
 
            var destinationFolder = @"C:\install\CSharp\TestkaustDoc";
            ClientContext ctx = new ClientContext("https://Some.some/some");
            //Configure the handler that will add the header.
            ctx.ExecutingWebRequest +=
            new EventHandler<WebRequestEventArgs>(ctx_MixedAuthRequest);
            //Set the Windows credentials.
            ctx.AuthenticationMode = ClientAuthenticationMode.Default;
            ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;
            // Get a reference to the SharePoint site
            var web = ctx.Web;
 
            // Get a reference to the document library
            var list = ctx.Web.Lists.GetByTitle("Dokumendid");
 
 
            // Get the list of files you want to export. I'm using a query
            // to find all files where the "Status" column is marked as "Approved"
            var camlQuery = new CamlQuery
            {
                ViewXml = @"<View>
                            <Query>
                                <Where>
                                <Eq>
                                    <FieldRef Name=""FileLeafRef"" />
                                    <Value Type=""Text"">" + $"{selectedFile}" + @"</Value>
                                </Eq>
                                </Where>
                                </Query>
                            </View>"
            };
            camlQuery.FolderServerRelativeUrl = "/prok/Shared Documents/Test";
            // Retrieve the items matching the query
            var items = list.GetItems(camlQuery);
 
            // Make sure to load the File in the context otherwise you won't go far
            ctx.Load(items, items2 => items2.IncludeWithDefaultProperties
                (item => item.DisplayName, item => item.File));
 
            // Execute the query and actually populate the results
            ctx.ExecuteQuery();
 
            // Iterate through every file returned and save them
            foreach (var item in items)
            {
          
                using (FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, item.File.ServerRelativeUrl))
                {
                    // Combine destination folder with filename -- don't concatenate
                    // it's just wrong!
                    var filePath = Path.Combine(destinationFolder, item.File.Name);
 
                    // Erase existing files, cause that's how I roll
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
 
                    // Create the file
                    using (var fileStream = System.IO.File.Create(filePath))
                    {
                        fileInfo.Stream.CopyTo(fileStream);
                    }
                }
 
            }
В начале как я понимаю мне нужно перенять данные которые выбраны и передать их в форму которую я использую.
Как это сделать?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
28.10.2019, 17:27
Ответы с готовыми решениями:

Как передать данные из Form2 в Form1
Привет. Есть две формы. На Form1 находиться listView1 с столбцами &quot;Имя&quot; &quot;Фамилия&quot;. Я открываю с...

Как передать данные между Program.cs и Form1.cs ?
Как передать данные между Program.cs и Form1.cs? Вот примерный код, того что необходимо...

Как передать данные между Form1 и Form2?
Есть клас Form1:Form. Надо передать значения в класс Form2 и назад. Как реализовать через get;set?

Передать данные из TexBox Form2 в ListView Form1
По нажатию на кнопку открывается форма2 там 3 текстбокса. Заполяю и передаю в Листвью первой формы....

2
172 / 118 / 57
Регистрация: 08.01.2013
Сообщений: 645
29.10.2019, 01:37 2
Советую почитать 2 пункт и его подпункты. Может найдешь ответ на свой вопрос.
0
0 / 0 / 0
Регистрация: 11.10.2019
Сообщений: 10
29.10.2019, 10:31  [ТС] 3
Всем спасибо. Получилось использовать одну форму. А именно через
C#
1
foreach (Form1 frm in System.Windows.Forms.Application.OpenForms)
Выглядит это так>
В Ribbon.cs я создаю форму>
C#
1
2
3
Form1 MallideVorm = new Form1();  //Creating form from Form1
 
          MallideVorm.Show(); // Showing form
Затем записываю в форму данные используя Application.OpenForms. Так как форма одна, то это работает.
C#
1
2
3
4
5
6
7
8
9
foreach (Form1 frm in System.Windows.Forms.Application.OpenForms)
                            {
                                if (frm.GetType() == typeof(Form1))
                                {
                                  
                                   
                                    Form1 frmTemp = (Form1)frm;
                               
                                   frm.addItemToListBoxFiles(file.Name);
А потом в Form1.cs тем же путем считываюданные с ListBox.
C#
1
2
3
4
5
6
foreach (Form1 frm in System.Windows.Forms.Application.OpenForms)
 
            {
                selectedFile =  FormFilesBox.SelectedItem.ToString();
                
            }
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
29.10.2019, 10:31
Помогаю со студенческими работами здесь

Как передать данные из Outlook в Word?
задача: программно открыть календарь в Outlook 2000, найти все встречи на текущую дату и поместить...

Как передать данные из datagridview в Excel / Word?
Здравствуйте. У меня есть шаблон в word, где прописаны метки, я открываю этот шаблон: //создание...

Почему на строку word=form1.pattern.value IE ругается: form1-определение отсутствует?
Почему на строку word=form1.pattern.value IE ругается: form1-определение отсутствует? pattern-...

Как добавить ссылку Microsoft.Office.Interop.Word?
Добрый день, подскажите пожалуйста как добавить ссылку Microsoft.Office.Interop.Word в студию, сам...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru