Show image from SQL Server 2008 in datagridview C# - image

I'm tired of searching for a solution. please help me.
I have a table with columns
p_id (int)
p_name (varchar50)
category (int)
price (money)
picture (Image)
Insertion process works perfectly, it is also showing me my database records.. but it sow me my filepath in gridview rather than show image...
Please help me... it is part of my project... and I don't know how to show retrieve image from database in Datagridview
I have done all my SQL connection work in Dall Class
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Image_task
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void insert_btn_Click(object sender, EventArgs e)
{
try
{
int count;
dall insert = new dall();
int id = Convert.ToInt32(id_txt.Text);
string name = name_txt.Text;
int cat = Convert.ToInt32(cat_txt.Text);
decimal price = Convert.ToDecimal(price_txt.Text);
string image=pic_txt.Text;
count = insert.insrt_up_del("insert into product values('" + id + "','" + name + "','" + cat + "','" + price + "','" + image + "')");
MessageBox.Show("Insert Successfully", "Successfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
insert_btn.Enabled=false;
}
private void browse_txt_Click(object sender, EventArgs e)
{
insert_btn.Enabled = true;
openFileDialog1.Filter = "Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" + "All files (*.*)|*.*";
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
pic_txt.Text = openFileDialog1.FileName;
}
}
private void search_btn_Click(object sender, EventArgs e)
{
dall select = new dall();
DataTable dt = new DataTable();
dt = select.select("Select * from product");
dataGridView1.DataSource = dt;
//DataGridViewImageColumn img = new DataGridViewImageColumn();
//img.DataPropertyName = "Picture";
//img.Width = 200;
//img.HeaderText = "Picture Column";
//img.ReadOnly = true;
//img.ImageLayout = DataGridViewImageCellLayout.Normal;
//dataGridView1.Columns.Add(img);
//dataGridView1.DataSource = new BindingSource(dt,null);
}
}
}

use data adapter
DataAdapter da = new DataAdapter("Select * from product",youconnection);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;

Related

Searching VARCHAR2 in oracle 11g DB

I am seraching varchar2 column "DF_FORM_COMP_VALUE" that includes ID Number with address to retrieve data by searching according to the ID Number only in oracle 11g DB. I built the following code to retrieve the data
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OracleClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String mycon = "DATA SOURCE=mydatasource/example;USER
ID=user;Password=mypassword;Unicode=True";
String myquery = "Select * From DF_FORM_COMP_VALUE Where VALUE_STR =" +
TextBox1.Text;
OracleConnection con = new OracleConnection(mycon);
OracleCommand cmd = new OracleCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
Label1.Text = "Particular ID found successfully";
Label2.Text = ds.Tables[0].Rows[0]["ID_TRANSACTION"].ToString();
Label3.Text = ds.Tables[0].Rows[0]["ID_FORM_COMPONENT"].ToString();
Label4.Text = ds.Tables[0].Rows[0]["ID"].ToString();
}
else
{
Label1.Text = "ID Not Found - Please Serach Again";
Label2.Text = "";
Label3.Text = "";
Label4.Text = "";
}
con.Close();
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
}
it keeps throwing Error ORA-01722: invalid number! Can someone help please
I'm assuming TextBox1.Text is some sort of input from the user on a web page somewhere? If the contents of that variable are "x", you're going to wind up with this query:
Select * From DF_FORM_COMP_VALUE Where VALUE_STR = x
That's not going to work because you need the string "x", but here it looks like a variable.
You probably want this line to look like:
String myquery = "Select * From DF_FORM_COMP_VALUE Where VALUE_STR = '" +
TextBox1.Text + "'";
THIS IS A VERY BAD IDEA. DO NOT DO THIS.
You need to read up on SQL Injection. Never put unsafe, user-specified text directly into a SQL query. Doing so will make your application trivially hackable.
I'm not sure what you're using to connect to Oracle, but you want to create a parameterized query and put the user input as a bind variable. One example on doing that is here. So you really want your query to look like this:
String myquery = "Select * From DF_FORM_COMP_VALUE Where VALUE_STR = :myinput"
Then you bind TextBox1.Text to :myinput, depending on what you're using to access Oracle. This is also more efficient if you run the query multiple times, because your query will not need to be hard parsed each time it is executed.

Bot Framework with LUIS - Issue with opening Form one after another

My bot is supposed to help delete appointment.
A prompt for user's nric will be done (in RetrieveAppt.cs)
Subsequently, if there is such user in my database, it should go on to prompt user to enter the apptId which he/she wants to delete (as there may be multiple appointments made by same person) (in DeleteAppt.cs)
Issue Description
Exception thrown: 'Microsoft.Bot.Builder.Internals.Fibers.InvalidNeedException' in Microsoft.Bot.Builder.dll
Code Example
RetrieveAppt.cs
using Microsoft.Bot.Builder.FormFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Bot.Models
{
[Serializable]
public class RetrieveAppt
{
[Prompt("Please provide your NRIC:")]
public string Nric { get; set; }
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendFormat(Nric);
return builder.ToString();
}
}
}
DeleteAppt.cs
using Microsoft.Bot.Builder.FormFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Bot.Models
{
[Serializable]
public class DeleteAppt
{
[Prompt("Please enter the appointment id that you wish to delete/cancel :")]
public string apptId { get; set; }
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendFormat(apptId);
return builder.ToString();
}
}
}
ApptLuisDialog.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.FormFlow;
using Microsoft.Bot.Connector;
using Bot.Models;
using System.Data.SqlClient;
using System.Globalization;
namespace Bot.Dialogs
{
[LuisModel("I have my own key", "I have my own key")]
[Serializable]
class ApptLuisDialog : LuisDialog<ApptLuisDialog>
{
String sql = #"Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=Temp.DB; User Id = (insert your username here); Password = (insert your password here); Integrated Security=true;MultipleActiveResultSets = true";
private static IForm<RetrieveAppt> BuildRetrieveForm()
{
var builder = new FormBuilder<RetrieveAppt>();
return builder.AddRemainingFields().Build();
}
private static IForm<DeleteAppt> BuildDeleteForm()
{
var builder = new FormBuilder<DeleteAppt>();
return builder.AddRemainingFields().Build();
}
[LuisIntent("")]
[LuisIntent("None")]
public async Task None(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: B");
await context.PostAsync("I'm sorry I don't understand you. However, I can help you to: \n\n" + "1) Retrieve Appointment \n\n" + "2) Create Appointment \n\n" + "3) Delete Appointment \n\n" + "4) Edit Appointment");
context.Wait(MessageReceived);
}
[LuisIntent("RetrieveAppointment")]
public async Task RetrieveAppointment(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: C");
var form = new RetrieveAppt();
var entities = new List<EntityRecommendation>(result.Entities);
var retrieveAppt = new FormDialog<RetrieveAppt>(form, BuildRetrieveForm, FormOptions.PromptInStart);
context.Call(retrieveAppt, RetrieveComplete);
}
private async Task RetrieveComplete(IDialogContext context, IAwaitable<RetrieveAppt> result)
{
RetrieveAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You cancelled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String nric = appt.Nric.ToString();
List<string> apptInfo = new List<string>();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command
SqlCommand cmd = new SqlCommand("SELECT * FROM Appointment a WHERE a.Nric ='" + nric + "'", con);
//Open sql connection
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String date = dr["AptDate"].ToString();
String[] temp = date.Split(null);
apptInfo.Add("Appointment ID: " + dr["ApptId"].ToString() + "\n\n"
+ "Nric: " + dr["Nric"].ToString() + "\n\n"
+ "Date: " + temp[0] + "\n\n"
+ "Time: " + dr["AptStartTime"].ToString() + "\n\n"
+ "Location: " + dr["Location"].ToString() + "\n\n"
+ "Purpose: " + dr["Purpose"].ToString());
}
//Close sql connection
dr.Close();
con.Close();
if (apptInfo.Count == 0)
{
await context.PostAsync("You do not have an appointment/no such NRIC");
}
else
{
for (int i = 0; i < apptInfo.Count(); i++)
{
await context.PostAsync("Your Appointment Info is: " + "\n\n" + apptInfo[i]);
}
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
[LuisIntent("DeleteAppointment")]
public async Task DeleteAppointment(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: A");
var form = new RetrieveAppt();
var retrieveAppt = new FormDialog<RetrieveAppt>(form, BuildRetrieveForm, FormOptions.PromptInStart);
context.Call(retrieveAppt, Delete);
}
private async Task Delete(IDialogContext context, IAwaitable<RetrieveAppt> result)
{
RetrieveAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You cancelled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String nric = appt.Nric.ToString().ToUpper();
List<string> apptInfo = new List<string>();
//SqlAdapter for inserting new records
SqlDataAdapter sda = new SqlDataAdapter();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command to check existing patient
SqlCommand cmd = new SqlCommand("SELECT * FROM Appointment a WHERE a.Nric ='" + nric + "'", con);
//Open sql connection
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String date = dr["AptDate"].ToString();
String[] temp = date.Split(null);
apptInfo.Add("Appointment ID: " + dr["ApptId"].ToString() + "\n\n"
+ "Nric: " + dr["Nric"].ToString() + "\n\n"
+ "Date: " + temp[0] + "\n\n"
+ "Time: " + dr["AptStartTime"].ToString() + "\n\n"
+ "Location: " + dr["Location"].ToString() + "\n\n"
+ "Purpose: " + dr["Purpose"].ToString());
}
if (apptInfo.Count != 0)
{
**//this is the part that has error, i can't prompt for the appointment id that user wants to delete**
System.Diagnostics.Debug.WriteLine("Entered here: AA");
var form = new DeleteAppt();
var deleteAppt = new FormDialog<DeleteAppt>(form, BuildDeleteForm, FormOptions.PromptInStart);
context.Call(deleteAppt, DeleteComplete);
}
else
{
//Close sql connection
dr.Close();
con.Close();
await context.PostAsync("Invalid NRIC/No current appointment");
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
private async Task DeleteComplete(IDialogContext context, IAwaitable<DeleteAppt> result)
{
DeleteAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You canceled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String apptId = appt.apptId.ToString();
List<string> newApptInfo = new List<string>();
//SqlAdapter for inserting new records
SqlDataAdapter sda = new SqlDataAdapter();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command to check existing patient
String cmd = "DELETE FROM Appointment a WHERE a.ApptId ='" + apptId + "'";
//Open sql connection
con.Open();
try
{
sda.InsertCommand = new SqlCommand(cmd, con);
sda.InsertCommand.ExecuteNonQuery();
//Close sql connection
con.Close();
await context.PostAsync("Appointment " + apptId + " cancelled successfully.");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception caught: " + ex);
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
}
}
Expected Behavior
For example, after bot prompts user to input NRIC, user inputs "123456". So let's say, there are 3 appointments linked to NRIC "123456". So it will show all 3 appointments (with the following details: apptId, apptDate, apptTime, locatoin) first.
Next, I want the bot to prompt the user for the appointment that he/she wants to delete base on the apptId. (But this prompt is not showing)
Actual Results
Exception thrown: 'Microsoft.Bot.Builder.Internals.Fibers.InvalidNeedException' in Microsoft.Bot.Builder.dll
Help needed here definitely
adding a "return" statement would solve it.
When making the call to context.Call(deleteAppt, DeleteComplete); there should not follow a call to context.Wait(MessageReceived). So add a return statement after context.Call(deleteAppt, DeleteComplete);
if (apptInfo.Count != 0)
{
//this is the part that has error, i can't prompt for the appointment id that user wants to delete
System.Diagnostics.Debug.WriteLine("Entered here: AA");
var form = new DeleteAppt();
var deleteAppt = new FormDialog<DeleteAppt>(form, BuildDeleteForm, FormOptions.PromptInStart);
context.Call(deleteAppt, DeleteComplete);
return;
}

The name does not exist in the current context

I'm trying to upload files to Oracle database Using C# vs2012. Its my first time I do so especially with Oracle. I just followed an example I found online but I got some errors before I even run the codes showing me that some of the type or name spaces don't exist.
The example I followed : Blob Example
Here are the codes that are underlined red in my Resources_to_upload.aspx.cs
objCmd
objConn
My code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
public partial class Resources_to_upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdUpload_Click(object sender, EventArgs e)
{
try
{
if (fileUploadDocument.PostedFile.ContentLength > 0)
{
// Get the File name and Extension
string FileName = Path.GetFileName(fileUploadDocument.PostedFile.FileName);
string FileExtension = Path.GetExtension(fileUploadDocument.PostedFile.FileName);
//
// Extract the content of the Document into a Byte array
int intlength = fileUploadDocument.PostedFile.ContentLength;
Byte[] byteData = new Byte[intlength];
fileUploadDocument.PostedFile.InputStream.Read(byteData, 0, intlength);
//
// Save the file to the DB
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
object Conn = new OracleConnection(strConn);
//
StringBuilder strQueryBuilder = new StringBuilder("INSERT INTO RESOURCES(RESOURCES_ID, FILE_NAME, TYPE, RESOURCE_FILE) VALUES (");
strQueryBuilder.Append("'1', ");
strQueryBuilder.Append("'" + FileName + "', ");
strQueryBuilder.Append("'" + FileExtension + "', ");
strQueryBuilder.Append(" :RESOURCE_FILE)");
String strQuery = strQueryBuilder.ToString();
//
OracleParameter blobParameter = new OracleParameter();
blobParameter.ParameterName = "Resources_FILE";
blobParameter.OracleType = OracleType.Blob;
blobParameter.Direction = ParameterDirection.Input;
blobParameter.Value = byteData;
objCmd = new OracleCommand(strQuery, objConn);
objCmd.Parameters.Add(blobParameter);
//
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
//
lblMsg.Text = "Document Uploaded Succesfully";
}
}
catch (Exception ex)
{
lblMsg.Text = " Error uploading Document: " + ex.Message.ToString();
}
}
}
Please help solve this issue. Thank you
StringBuilder is in the System.Text namespace. So you can either reference it explicitly:
System.Text.StringBuilder strQueryBuilder ...
Or add a using directive to the file:
using System.Text
...
StringBuilder strQueryBuilder ...
As for objCmd and objConn, where do you define those? They're not created in the code you posted. You do create a connection object here:
object Conn = new OracleConnection(strConn);
Maybe you mean to use Conn instead of objConn? But you don't create a command object anywhere. You need to declare and instantiate variables before you can use them.

Cannot set permission for documents on Visual web part Sharepoint 2010 Foundation

Good day! I have an event handler that, when you add a document to the library redirects the user to a web form with the parameters of the document. In the web form, it displays the current user in the form of Checkboxlist. The user selects the appropriate group, and he presses the Save button. Following are assigned permissions to the document according to the selected group. The problem is that the resolution of the document is not assigned according to selected groups. Here's the handler code:
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Web;
using System.IO;
namespace SharePointProject3.EventReceiver2
{
/// <summary>
/// События элемента списка
/// </summary>
public class EventReceiver2 : SPItemEventReceiver
{
private HttpContext _context;
public EventReceiver2()
{
_context = HttpContext.Current;
}
public override void ItemAdding(SPItemEventProperties properties)
{
//Временно отключаем срабатывание обработчика
EventFiringEnabled = false;
//Получаем файл из HttpContext
HttpPostedFile file = _context.Request.Files[0];
Stream fileStream = file.InputStream;
byte[] fileByte = new byte[file.ContentLength];
fileStream.Read(fileByte, 0, file.ContentLength);
//Загружаем файл в библиотеку документов
SPFile fileUploded = properties.Web.Files.Add(properties.AfterUrl, fileByte);
//Включаем обработчик обратно
EventFiringEnabled = true;
//Отменяем добавление файла, которое делал пользователь
properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
//Деламе редирект
properties.RedirectUrl = properties.Web.Url + "/test_perm/default.aspx?ID=" + fileUploded.UniqueId;
}
}
}
And here's the code of the Web Part:
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using Microsoft.SharePoint.Utilities;
namespace CustomGroupAssignment.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
using (SPSite site = new SPSite("http://kviten:83/"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser currentUser = web.CurrentUser;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
SPGroupCollection webGroups = currentUser.Groups;
CheckBoxList1.DataSource = webGroups;
CheckBoxList1.DataValueField = "ID";
CheckBoxList1.DataTextField = "Name";
CheckBoxList1.DataBind();
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = true;
}
try
{
string itemID = Page.Request.Params["ID"];
SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/DocLib2/Forms/AllItems.aspx"));
SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
}
catch (Exception ex)
{
//Выводим ошибку
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("http://kviten:83/"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser currentUser = web.CurrentUser;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
try
{
string itemID = Page.Request.Params["ID"];
SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/Test_Doc_Lib/"));
SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
//Break the role inheritance from List and remove any RoleAssignments
//item.BreakRoleInheritance(false);
//while (item.RoleAssignments.Count > 0)
//{
// item.RoleAssignments.Remove(0);
//}
if (!item.HasUniqueRoleAssignments)
{
item.ResetRoleInheritance();
item.Update();
item.BreakRoleInheritance(false);
item.Update();
}
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected) //Response.Write("- " + li.Text + "<br/>");
{
// Give permissions to a specific group
SPGroup group = web.Groups.GetByID(Convert.ToInt32(li.Value));
SPPrincipal principalGroup = group;
SPRoleAssignment roleassignment_group = new SPRoleAssignment(group);
SPRoleAssignment roleAssignment = item.RoleAssignments.GetAssignmentByPrincipal(principalGroup);
item.RoleAssignments.Add(roleAssignment);
item.Update();
}
}
}
catch (Exception ex)
{
//Выводим ошибку
}
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();
}
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();
}
}
}
I can not understand why I cannot assign permissions to the document! Help please!
If you use the / / Response.Write ("-" + li.Text + "<br/>"); which commented out, we can see that the checkboxes are not selected and not displayed. item.ResetRoleInheritance(); executed and permission assigned to only the current user with no groups. In what could be the reason?
The right solution for a web part:
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using Microsoft.SharePoint.Utilities;
namespace CustomGroupAssignment.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
using (SPSite site = new SPSite("http://kviten:83/"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser currentUser = web.CurrentUser;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
SPGroupCollection webGroups = currentUser.Groups;
CheckBoxList1.DataSource = webGroups;
CheckBoxList1.DataValueField = "ID";
CheckBoxList1.DataTextField = "Name";
CheckBoxList1.DataBind();
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = true;
}
try
{
string itemID = Page.Request.Params["ID"];
SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/DocLib2/Forms/AllItems.aspx"));
SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
}
catch (Exception ex)
{
//Выводим ошибку
}
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("http://kviten:83/"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser currentUser = web.CurrentUser;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
string itemID = Page.Request.Params["ID"];
SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/Test_Doc_Lib/"));
SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected) //Response.Write("- " + li.Text + "<br/>");
{
if (!item.HasUniqueRoleAssignments)
{
item.ResetRoleInheritance();
item.Update();
}
item.BreakRoleInheritance(false);
item.Update();
SPGroup group = web.Groups.GetByID(Convert.ToInt32(li.Value));
SPPrincipal principalGroup = (SPPrincipal)group;
//SPRoleAssignment roleassignment_group = new SPRoleAssignment(principalGroup);
SPRoleAssignment roleAssignment = item.Web.RoleAssignments.GetAssignmentByPrincipal(principalGroup);
item.RoleAssignments.Add(roleAssignment);
item.Update();
// var roleAssignment = new SPRoleAssignment(principalGroup);
// item.RoleAssignments.Add(roleAssignment);
// item.Update();
}
}
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();
}
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();
}
}
}

dynamically generated pageview issue

I have created dynamic tab function. When i create dynamic tab it will create pageview for that tab. But when i deleted that tab that pageview is not deleting. Can any one help me to fix this.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.WebControls;
using Telerik;
public partial class Radstrip2 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label PageContent;
protected System.Web.UI.WebControls.Repeater BuildingSummary;
protected Telerik.WebControls.PageView PageView1;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Tab tab = new Tab();
tab.Text = string.Format("New Page {0}", 1);
RadTabStrip1.Tabs.Add(tab);
PageView pageView = new PageView();
RadMultiPage1.PageViews.Add(pageView);
BuildPageViewContents(pageView, RadTabStrip1.Tabs.Count);
RadTabStrip1.SelectedIndex = 0;
}
}
private void BuildPageViewContents(PageView pageView, int index)
{
pageView.ID = "Page " + index.ToString();
pageView.Controls.Add(new LiteralControl(" <B>New page</B>" + (index).ToString()));
}
protected void Button1_Click(object sender, EventArgs e)
{
Tab tab = new Tab();
tab.Text = string.Format("New Page {0}", RadTabStrip1.Tabs.Count + 1);
RadTabStrip1.Tabs.Add(tab);
PageView pageView = new PageView();
pageView.ID = "Page " + pageView.Index.ToString();
RadMultiPage1.PageViews.Add(pageView);
BuildPageViewContents(pageView, RadTabStrip1.Tabs.Count);
RadTabStrip1.SelectedIndex = RadTabStrip1.SelectedIndex + 1;
RadMultiPage1.SelectedIndex = RadTabStrip1.SelectedIndex;
}
protected void Button2_Click(object sender, EventArgs e)
{
Tab currentTab = RadTabStrip1.InnerMostSelectedTab;
if (currentTab != null)
{
ITabContainer owner = currentTab.Owner;
owner.Tabs.Remove(currentTab);
//RadMultiPage1.PageViews.Remove(currentTab.PageView);
if (owner.Tabs.Count > 0)
{
owner.SelectedIndex = 0;
}
}
}
protected void RadMultiPage1_PageViewItemCreated1(PageView view, int viewIndex)
{
BuildPageViewContents(view, viewIndex + 1);
}
}
I see that in your Button2_Click() method you remove the currently selected tab but you don't remove the current page view. You can try with:
RadMultiPage1.PageViews.RemoveAt(RadMultiPage1.SelectedIndex);
This should remove the currently selected page view

Resources