Entity Framework CheckboxList Database Insert - entity-framework

UPDATED:
I'm using a Detailsview Insert Control and I am trying to create a new row in the database from a checkbox in a CheckBoxList. I'm getting the "The INSERT statement conflicted with the FOREIGN KEY constraint"
Here is my cs:
protected void AddPrincipleStaffDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
CheckBoxList PrincipleStaffTitle = (CheckBoxList)FindControl("PrincipleStaffTitle");
if (PrincipleStaffTitle != null)
{
foreach (ListItem item in PrincipleStaffTitle.Items)
{
if (item.Selected)
{
string stringSession = Session["ProductionID"].ToString();
int intProductionID = Int32.Parse(stringSession);
var ID = item.Value;
using (var context = new FactoryTheaterModelFirstContainer())
{
PrincipleStaff principlestaff = new PrincipleStaff();
principlestaff.PrincipleStaffTitle = ID;
principlestaff.Production_proProductionID = intProductionID;
context.PrincipleStaffs.Add(principlestaff);
context.SaveChanges();
}
}
}
}
here is the aspx:
<asp:EntityDataSource ID="PrincipleStaffSource" runat="server" ConnectionString="name=FactoryTheaterModelFirstContainer" DefaultContainerName="FactoryTheaterModelFirstContainer" EnableFlattening="False" EntitySetName="PrincipleStaffs" EntityTypeFilter="PrincipleStaff" EnableInsert="True"></asp:EntityDataSource>
<asp:DetailsView ID="AddPrincipleStaffDetailsView" runat="server" AutoGenerateRows="False" DataKeyNames="PrincipleStaffID" DataSourceID="PrincipleStaffSource" Height="50px" Width="730px" DefaultMode="Insert" OnItemInserting="AddPrincipleStaffDetailsView_ItemInserting" OnItemInserted="AddPrincipleStaffDetailsView_ItemInserted">
<Fields>
<asp:TemplateField HeaderText="Add Principle Staff Role:" SortExpression="PrincipleStaffTitle">
<InsertItemTemplate>
<asp:CheckBoxList ID="PrincipleStaffTitle" runat="server" SelectedValue='<%# Bind("PrincipleStaffTitle") %>'>
<asp:ListItem Value="Director">Director(s)</asp:ListItem>
<asp:ListItem Value="Assistant Director">Assistant Director(s)</asp:ListItem>
<asp:ListItem Value="Written By">Written By(s)</asp:ListItem>
<asp:ListItem Value="Executive Producer">Executive Producer(s)</asp:ListItem>
<asp:ListItem Value="Producer">Producer(s)</asp:ListItem>
<asp:ListItem Value="Techincal Director">Technical Director(s)</asp:ListItem>
</asp:CheckBoxList>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PrincipleStaffTitle") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
The Production.proProductionID is the foreign key that I'm trying to get into the PrincipleStaff Production_proProductionid column. I can't seem to create the FK relationship.
Thanks for any help that can be provided!

The Below code works. I've since moved my context.savechanges(); outside the loop. My issue was happening on my ItemInserted command.
protected void AddPrincipleStaffDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
CheckBoxList PrincipleStaffCheckBox = (CheckBoxList)AddPrincipleStaffDetailsView.FindControl("PrincipleStaffTitleCheckBoxList");
if (PrincipleStaffCheckBox.Items.Count > 0)
{
foreach (ListItem item in PrincipleStaffCheckBox.Items)
{
if (item.Selected)
{
string stringSession = Session["ProductionID"].ToString();
int intProductionID = 0;
intProductionID = Int32.Parse(stringSession);
var principlestafftitle = item.Value;
try
{
using (var context = new FactoryTheaterModelFirstContainer())
{
Production proid = context.Productions.Single(i => i.proProductionID == intProductionID);
PrincipleStaff principlestaff = new PrincipleStaff()
{
PrincipleStaffTitle = principlestafftitle,
Production_proProductionID = intProductionID
};
proid.PrincipleStaffs.Add(principlestaff);
context.SaveChanges();
}
}
catch (Exception f)
{
Console.WriteLine(f); // or log to file, etc.
throw; // re-throw the exception if you want it to continue up the stack
}
}
}
}
}

Related

trouble with DataGrid.RowDetailsTemplate to use access command method

the xaml code is:
<DockPanel>
<DataGrid x:Name="Quote" AutoGenerateColumns="False">
<DataGrid.Columns >
<DataGridTextColumn Header="Code" Binding="{Binding Code}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Quantities" Binding="{Binding Quantities}"/>
<DataGridTextColumn Header="Price" Binding="{Binding Price}"/>
<DataGridTextColumn Header="Cost" Binding="{Binding Cost}"/>
<DataGridCheckBoxColumn Header="Done" Binding="{Binding Done}"/>
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Border BorderThickness="0" Background="Beige" Padding="10">
<StackPanel Orientation="Horizontal">
<Button Command="{Binding Path=DataContext.Renew1Command, RelativeSource= {RelativeSource FindAncestor,AncestorType=DataGrid}}">Call Command</Button>
</StackPanel>
</Border>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</DockPanel>
the model is:
public class StockModel
{
public event PropertyChangedEventHandler PropertyChanged;
public void propChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
private string code;
public string Code
{
get { return code; }
set
{
code = value;
this.propChanged("Code");
}
}
....
private bool done;
public bool Done
{
get { return done; }
set
{
done = value;
this.propChanged("Done");
}
}
public DelegateCommand Renew1Command;
public void Renew1(object obj)
{
MessageBox.Show("Hello Command");
System.Console.WriteLine("Hello Command");
}
public StockModel()
{
Renew1Command = new DelegateCommand();
this.Renew1Command.ExecuteAction += this.Renew1;
}
}
Finally i init the datasource by:
List<StockModel> stockList = new List<StockModel>();
stockList.Add(new StockModel() { Code = "601919", Cost = "8888", Name = "CIB", Done = true, Price = "16.1", Quantities = "200" });
stockList.Add(new StockModel() { Code = "601919", Cost = "8888", Name = "CIB", Done = false, Price = "16.1", Quantities = "100" });
stockList.Add(new StockModel() { Code = "601919", Cost = "8888", Name = "CIB", Done = true, Price = "16.1", Quantities = "100" });
stockList.Add(new StockModel() { Code = "601919", Cost = "8888", Name = "CIB", Done = true, Price = "16.1", Quantities = "200" });
this.Quote.ItemsSource = stockList;
the DataGridTextColumn can display the data of binding source,
but i can't click button of DataTemplate to call corresponding action from model.
how to fix the binding?
Call Command
move to StockModel class, replace "public DelegateCommand Renew1Command;" with "public DelegateCommand Renew1Command { get; set; }".
the problem will be solved.

Customized GridView - AddCustomControlsRow on PreRender empties DataRows

I´m trying to create a custom GridView with additional functionality but I do have problem with PostBack which are "simulated" by "Button2". On every PostBack (after a first DataBinding) the content of one DataRow gets erased until the GridView is fully empty. It has something to do with AddCustomControls() within the PreRender event. But I don´t know how to fix this issue. Does anybody have an idea? Any help would be greatly appreciated.
Maybe the image below describes the behavior better than my words do.
With DataBind() in the OnLoad event and AddCustomControls in the OnDataBound event it worked pretty well. The table stayed exactly the same between PostBacks. But I couldn´t use this "solution" (which is also not very elegant) anymore when I tried to implement the editing of the grid. Logically the edited values within the TextBoxes were overriden by the DataBind() in OnLoad.
Somehow it has to do with "headerTable.Rows.AddAt(1, controlRow);". If I do "headerTable.Rows.Add(controlRow);" which adds the row at the end everything works finde. So the content AFTER this kind of header row get cleared...
Web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<pages>
<controls>
<add tagPrefix="asp" assembly="WebApplication11" namespace="WebApplication11"/>
</controls>
</pages>
</system.web>
</configuration>
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:mightygridview
ID="mightyGridView"
runat="server"
AllowSorting="true"
AllowHiding="true"
AutoGenerateEditButton="false"
OnRowUpdating="mightyGridView_RowUpdating">
</asp:mightygridview>
<br />
<asp:Button ID="Button1" runat="server" Text="Button - Binding" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button - Nothing" />
</div>
</form>
</body>
</html>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable tbl = new DataTable();
DataRow row;
tbl.Columns.Add("Spalte A");
tbl.Columns.Add("Spalte B");
tbl.Columns.Add("Spalte C");
row = tbl.NewRow();
row[0] = "Spalte A, Zeile 1";
row[1] = "Spalte B, Zeile 1";
row[2] = "Spalte C, Zeile 1";
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = "Spalte A, Zeile 2";
row[1] = "Spalte B, Zeile 2";
row[2] = "Spalte C, Zeile 2";
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = "Spalte A, Zeile 3";
row[1] = "Spalte B, Zeile 3";
row[2] = "Spalte C, Zeile 3";
tbl.Rows.Add(row);
mightyGridView.DataSource = tbl;
mightyGridView.DataBind();
}
MightyGridView.cs
public class MightyGridView : GridView
{
public MightyGridView()
{
_images = new Dictionary<_imageTypes, string>();
_images.Add(_imageTypes.SortAsc, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOwwAADsMBx2+oZAAAAAd0SU1FB9oGEAstLlCBjxcAAABWSURBVBjTY/z45TsDqYCFkYF0wMTAyMiADW/ese8/LjkmbCZt3r73PzKNYRMjAwMDMkZXuHn73v/oalBs2oTDZHRxJph2XBpQNELVMn759pOM0CMDAADRtiJL6bIYOQAAAABJRU5ErkJggg==");
_images.Add(_imageTypes.SortAscActive, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9oHDgckDaeYtVQAAAA1SURBVBjTY/z//z8DqYCJgQyAU5NK2Yb/JGmCacClkYmQDdg0MhHjJHRxJmL8gC7PSLcgBwAAMRqcsjcZIwAAAABJRU5ErkJggg==");
_images.Add(_imageTypes.SortDesc, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOwwAADsMBx2+oZAAAAAd0SU1FB9oGEAstDmvvr98AAABhSURBVBjTY/zy7ScDqYCJgQzA8p/hPwMDAwPDpm17/xNS7OflzAix6T8DA8N/BgY/T4gATg2ezowwtUwYErg0IPsJqhmOfdEU+Ho6M6KrwRoQMI2+OGxm/PTlOzmhRzoAADvsH5oZ616EAAAAAElFTkSuQmCC");
_images.Add(_imageTypes.SortDescActive, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9oHDgckFi39fLgAAABBSURBVBjTY/z//z8DqYCJgQzAAmOolG0gaOWdrgBGFJtgAoQ0YDgPl0Z0cSZCCrAa9P//f6xYuXT9f1xyjHQLcgCoNDp3uWsOTwAAAABJRU5ErkJggg==");
_images.Add(_imageTypes.HideColumn, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9oGEAsyFSzQaK0AAADHSURBVBjThZAxCoNQDIbTnsAbCM4eQfAC4uYstCdwFOd2dXNwFZzcxQtI3+bkrIKz4AW+Ln2l7WtpIJB8yf9DIoAAsq4rVVWx77topnMcR6ZpQvdHecS2bXJTSrIsYxgGNE/TFKWU2LZ90MxwvVwvBEFAXdd4nodSis8dQwTI6XTGsiz6vufb3ABd1+G6Lnme4/v+f9E8zziOQ1mWAFIUxbP+KYqiyHCP49gQPb8nIrIsi4Rh+IokSRJp25Y3+OrQNM3XGz7zDsbcHXO0jDwtAAAAAElFTkSuQmCC");
_images.Add(_imageTypes.ShowAllColumns, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAfCAIAAAB/DupQAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAYdSURBVEhLtZXrb5NlGMb3/6AQjXzigyQaEwwGDDGixGDYQEUSFUWDcnACE7fhtq4HtpX2LV27Hmi7Q0e3MTbWLJtkAyY4NybqGId1Ze16Prynet3P87Yj+4zNnSZ7CL9cua7rvltl6F3FtPastgSeNfmjjd7oL+6Vc85Irf3pKeHJccvjDXOs/dFXpodH9Iuftvxb8+s/Hzf8/dH5Bx/U/fX+2YX3frq/p3b+3dPzu07N5fP5KkDnnpZmn5TuPS79vlS6s1gKz6vfdjyaWFDHF9TwnDZX76h7zy7gz7E5dXRWHflDvXZX8U4qeAzeUnqmlCuTsmdS6gxL9QHxtcN3VlZWquo90ZnFUrH8uRCIXexPfK5bxP+sPOr6UqZQZucPf4JSeTznSTb4s3g0D0uVx1p3+hshtblmemlpqerHy8uhGaXrRgz/XOdaPnE5VudN7K9/0ODPHOuI4PFMV+yQfvXrS4ntR++2hsQ6VxSP31mj+5sTB1rTeDzhyFc3LeOxORDbfSb61umVTQemCH1Yt/Thzw/21C7sOnn/nRPzO47PvXls9vWj97Z9cRffWw/PbJhXP7m95dDtLQdvbT546+Wa6ZeqtdlUPQViZQh92TdaYh+VDz6KOj49pyglWVElWZFkVaRRwlOzRUkpiHKhqOQLSq4o5wryyMRMNi9n8lI6J6eyUiorJjPS7urvCS103+BUVRtVUdTuoZv4BpQPuKKk+EITBVHJg8ugmGxBdnaPMq6UJq6UzIqJjLR9zxFC2wOjjMvlEhdi/QMT+JbBlTDEhV5PMAwo0FxvtiBl8nKnfyiTk1JskkBnpERG3LqjWjOE+UADLke7e0fJCknlUBpRcfiHCQ29RRkmkA85yeruh1ioJm6WuIl0GW29cj18czYw9Jt/YNIXGvcEx5yBYbs3hBffwIS3f9zdN+bsvt7pGxRcQXcw7OodcwTw55DgCVmcfe32gM03LHiHrJ5BiztkdoX0Qq+m2ua5piolhSSTahYdeU3RwQqR9DKLZRhCVkAvWSFlcjLE2rxDZYvhsriWxhQ1tMU7zLjMinJu0As0oGUuoZ29I2QxoGQFcdNZ0erqT2aoFWucmyrGU2VDzF2DG7iwGAK5v6SXtQJ6kRgqwarGuIguK5kdfUDDXwygmFiyrJqjyQfeYhYdEmMVrlRNyRYUCGQ+sAozbiojmmx+QLkPcUhOPoduc4bGbt57LrGRTt+AdT2xEbt/yOYZQGId9gDF5UZ6wQ5Hb5stYBK8BovbZO822gIGwa+z+HRmT4PRpXlt6grJClZO4XtRlFTodfeFC5UKs6pBr+AZYJLZamRYhdOiSQiQ3nQxlqJZTdJo6HZHqMLlLYYPnagw3MA2o8W8EjnJ7AxyH4jLKgwf9BYP+cu4cBncZ4ky+qK9n1YZFovrlRA8/XyVMeQvVjkvocJsNagPiI75K7Z0uGBxRS+46+hWR5+2dbxqRVINW2nleB+oZ1QJo8Wd4j6gEmhbClUTm9vsQHMfVpMFQq8VNEP0wtX/K8ZWoYf3F9eSXzUMYtzQX1iMGHmF4UOctRg+IEbuL9NbjK4VMJrqJmtgw9bBX8TIVk7rA48OMSbSUnnlEBpVGDFqaMZdYaOhm81XSDLpRR+oEtCLGLWVY1cYA38RI4+O58b7gBhh7rMEieXoSLyCvuRjXHYtGReDGEkyv+48tzTFqHGZXsotUUSM0QT0Mslx4kZiZTQaMhiedtAhHRTc/WZHb7vgM5qdVveAxYWt626z+U1Wr8Hs1Ld3GgW/weLVm926dmdLm6PZZG82CheMjkZjZ4PBXm+w1ettPzUJ6w3hP0jl604W2zyD7FRSf/lVQ27gxtj14XqRG5ReMHZWfFiJ5yF5eV210AOLUWG2GtRfumfOoLYa2umha4nENIsTrL/wN1FoNNgourIVMGQ5ll9vCK0GobVTSdshBKhnWtXoRMSTsNWprTJWo9yHep0ALtfLZ3m1jEZD+PXhP8y8D40GJ/ZNu5bsCgN9XmfjW4dKaLmtFc41WSPgxvPLTC+4z6Ev+Q4crdv72cm39325bWfNK2/seyFDv+i5XC4SiTx80R8w/wMqxePff8NAaAAAAABJRU5ErkJggg==");
}
private enum _imageTypes { SortAsc, SortAscActive, SortDesc, SortDescActive, HideColumn, ShowAllColumns }
private readonly Dictionary<_imageTypes, string> _images;
public new bool AllowSorting { get; set; }
public bool AllowHiding { get; set; }
public override object DataSource
{
get
{
return Page.Session[this.ID + ".DataSource"];
}
set
{
Page.Session[this.ID + ".DataSource"] = value;
base.DataSource = value;
}
}
private void AddCustomControlsRow()
{
if (DataSource != null)
{
if (AllowSorting || AllowHiding)
{
DataTable dataTable = GetDataTableFromDataSource();
if (dataTable.Columns.Count > 0 && dataTable.Rows.Count > 0)
{
if (this.HeaderRow != null && this.HeaderRow.Parent != null)
{
string sortExpression = dataTable.DefaultView.Sort.Replace(" ASC", "").Replace(" DESC", "");
SortDirection sortDirection = dataTable.DefaultView.Sort.EndsWith(" ASC") ? SortDirection.Ascending : SortDirection.Descending;
Table headerTable = (Table)this.HeaderRow.Parent;
GridViewRow controlRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell controlCell;
ImageButton imageButton;
foreach (TableCell cell in this.HeaderRow.Cells)
{
// Sicherstellen, dass es nicht die Spalte mit den Bearbeiten-Buttons ist, welche keine Überschrift enthält.
if (!(cell.Text.Replace(" ", "").Trim().Length > 0))
{
controlCell = new TableCell();
cell.Attributes.Add("style", "border-bottom: 0");
controlCell.Attributes.Add("style", "border-top: 0; text-align: center");
controlRow.Cells.Add(controlCell);
}
else
{
controlCell = new TableCell();
cell.Attributes.Add("style", "border-bottom: 0");
controlCell.Attributes.Add("style", "border-top: 0; text-align: center");
if (AllowSorting)
{
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(SortColumnAscButton_Click);
if (sortExpression == cell.Text && sortDirection == SortDirection.Ascending)
imageButton.ImageUrl = _images[_imageTypes.SortAscActive];
else
imageButton.ImageUrl = _images[_imageTypes.SortAsc];
controlCell.Controls.Add(imageButton);
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(SortColumnDescButton_Click);
if (sortExpression == cell.Text && sortDirection == SortDirection.Descending)
imageButton.ImageUrl = _images[_imageTypes.SortDescActive];
else
imageButton.ImageUrl = _images[_imageTypes.SortDesc];
controlCell.Controls.Add(imageButton);
controlRow.Cells.Add(controlCell);
}
if (AllowHiding)
{
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(HideColumnButton_Click);
imageButton.ImageUrl = _images[_imageTypes.HideColumn];
controlCell.Controls.Add(imageButton);
controlRow.Cells.Add(controlCell);
}
}
}
headerTable.Rows.AddAt(1, controlRow);
}
}
}
}
}
public static DataTable GetDataTableFromIEnumerable(IEnumerable enumerable)
{
DataTable dataTable = new DataTable();
DataRow row;
PropertyInfo[] propertyInfos;
foreach (object obj in enumerable)
{
propertyInfos = obj.GetType().GetProperties();
if (dataTable.Columns.Count == 0)
foreach (PropertyInfo pi in propertyInfos)
dataTable.Columns.Add(pi.Name, pi.PropertyType);
row = dataTable.NewRow();
foreach (PropertyInfo pi in propertyInfos)
{
object value = pi.GetValue(obj, null);
row[pi.Name] = value;
}
dataTable.Rows.Add(row);
}
return dataTable;
}
private DataTable GetDataTableFromDataSource()
{
DataTable dataTable;
if (DataSource is DataTable)
dataTable = (DataTable)DataSource;
else if (DataSource is IEnumerable)
dataTable = GetDataTableFromIEnumerable((IEnumerable)DataSource);
else
throw new NotSupportedException("Typ wird nicht unterstützt.");
return dataTable;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
// Weg der funktionierte, jedoch mit Editing Probleme macht: OnLoad: DataBind() / OnDataBound: AddCustomControls.
// Das DataBinding überschrieb die geänderten Werte wieder.
base.OnLoad(e);
}
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
}
protected override void OnPreRender(EventArgs e)
{
AddCustomControlsRow();
base.OnPreRender(e);
}
protected override void OnUnload(EventArgs e)
{
base.OnUnload(e);
}
protected void SortColumnAscButton_Click(object sender, ImageClickEventArgs e)
{
DataTable dataTable = GetDataTableFromDataSource();
dataTable.DefaultView.Sort = ((ImageButton)sender).Attributes["data-column-name"] + " ASC";
DataSource = dataTable;
DataBind();
}
protected void SortColumnDescButton_Click(object sender, ImageClickEventArgs e)
{
DataTable dataTable = GetDataTableFromDataSource();
dataTable.DefaultView.Sort = ((ImageButton)sender).Attributes["data-column-name"] + " DESC";
DataSource = dataTable;
DataBind();
}
protected void HideColumnButton_Click(object sender, ImageClickEventArgs e)
{
// todo: Improve. Backup zum resetten, etc.
DataTable dataTable = GetDataTableFromDataSource();
dataTable.Columns.Remove(((ImageButton)sender).Attributes["data-column-name"]);
DataSource = dataTable;
DataBind();
}
Moved it to OnRowCreated which is also fired on every PostBack of the life cycle:
protected override void OnRowCreated(GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
if (AllowSorting || AllowHiding)
AddHeaderControls(e.Row);
}
base.OnRowCreated(e);
}
It also fixed the behavior of the sort buttons etc. A click on a (sort) button did not trigger the event because the "binding" in the PreRender is too late to handle the event.
I also changed the AddHeaderControls method a bit, instead of adding a whole row, I add the controls to the cell itself, here is a snippet:
foreach (TableCell cell in row.Cells)
{
// Sicherstellen, dass es nicht die Spalte mit den Bearbeiten-Buttons ist, welche keine Überschrift enthält.
if (cell.Text.Replace("&nbsp;", string.Empty).Trim().Length > 0)
{
// Write the Header Text into the cell as a (Literal)Control, because it would be lost otherwise.
cell.Controls.Add(new LiteralControl(cell.Text));
cell.Controls.Add(new LiteralControl("<br />"));
if (AllowSorting)
{
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(SortColumnAscButton_Click);
if (sortExpression == cell.Text && sortDirection == SortDirection.Ascending)
imageButton.ImageUrl = _images[_imageTypes.SortAscActive];
else
imageButton.ImageUrl = _images[_imageTypes.SortAsc];
cell.Controls.Add(imageButton);
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(SortColumnDescButton_Click);
if (sortExpression == cell.Text && sortDirection == SortDirection.Descending)
imageButton.ImageUrl = _images[_imageTypes.SortDescActive];
else
imageButton.ImageUrl = _images[_imageTypes.SortDesc];
cell.Controls.Add(imageButton);
}
if (AllowHiding)
{
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(HideColumnButton_Click);
imageButton.ImageUrl = _images[_imageTypes.HideColumn];
cell.Controls.Add(imageButton);
}
}
}

Populating ListBox in ASP.NET MVC from SQL CE (C#)

I can't find an example that suits my needs anywhere, so I'm asking you guys.
Im trying to populate a ListBox on my website with content from an SQL CE database.
I used Asp.Net MVC DropDownList Data Binding as an example to create my ListBox.
I have now hit a deadend and could use some help, here is what i got:
Index.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Headline</h2>
<% using (Html.BeginForm())
{ %>
<%= Html.ListBoxFor(x => x.SelectedItemId, new SelectList(Model.Items, "Value", "Text"))%>
<br /><input type="submit" value="Show" style="width: 72px" />
<% } %>
</asp:Content>
HomeController.cs
public ActionResult Index()
{
var model = new ItemsViewModel();
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=|DataDirectory|\RSSdb.sdf;Persist Security Info=False"))
{
con.Open();
string cmdString = string.Format("SELECT Name, ID FROM TableIndex WHERE (Active = N'true')");
using (SqlCeCommand cmd = new SqlCeCommand(cmdString, con))
{
using (SqlCeDataReader dataRead = cmd.ExecuteReader())
{
model = new ItemsViewModel
{
Items = new[]
{
new SelectListItem { Value = "Foo", Text = "Foo" } ,
new SelectListItem { Value = "Bar", Text = "Bar" }
}
};
}
}
}
return View(model);
}
ItemsViewModel.cs
public class ItemsViewModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Now what i need is to have the code in HomeController.cs be something like this:
model = new ItemsViewModel
{
Items = new[]
{
While(dataRead.Read())
{
new SelectListItem { Value = dataRead["ID"], Text = dataRead["Name"] };
}
}
};
But this don't work, and i have no idea how else to do it, all help is appreciated.
You've probably realized by now that you can't put a while loop within an array initializer. One approach to solving this would be to create a method which will build the list for you like so:
public IList<SelectListItem> GetSelectListItems()
{
IList<SelectListItem> items = new List<SelectListItem>();
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=|DataDirectory|\RSSdb.sdf;Persist Security Info=False"))
{
con.Open();
string cmdString = "SELECT Name, ID FROM TableIndex WHERE (Active = N'true')";
using (SqlCeCommand cmd = new SqlCeCommand(cmdString, con))
{
using (SqlCeDataReader dataRead = cmd.ExecuteReader())
{
while(dataRead.Read())
{
items.Add(new SelectListItem
{
Value = dataRead["ID"],
Text = dataRead["Name"]
});
}
}
}
}
return items;
}
Then your action could be as simple as:
public ActionResult Index()
{
var model = new ItemsViewModel
{
Items = GetSelectListItems()
};
return View(model);
}

ObjectDatasource passing parameters

I want to Insert data from textboxes using ObjectDatasource. The ObjectDataSource is bound to a gridview but displays certain computed columns only. The Textboxes are used to input all the basic inputs.
ObjectDatasource Delete & Select commands (Link buttons on gridview) are working. However I am having trouble with Insert command. I am not able to figure out how to pass the data from the textboxes as parameters to the ObjectDataSource Insert
EDIT: With the code below, a record is getting inserted. Parameters are getting passed. odssMain.Insert() gives the Error: "Object reference not set to an instance of an object".
EDIT: WHY AM I GETTING THIS ERROR?
Also the ObjectDataSource has been acting weird. After an error, I have to reconfigure the Insert Method again on the ODS Wizard as the method will be blank.
ASP.NET 3.5 & SQL 2008, VS 2008.
Here's my code:
<asp:ObjectDataSource ID="odsMain" runat="server"
SelectMethod="SelectMain" DeleteMethod="DeleteMain"
InsertMethod="InsertMain" UpdateMethod="UpdateMain"
OldValuesParameterFormatString="original_{0}" TypeName="MainDB" >
.......
<InsertParameters>
<asp:Parameter Name="Quantity" Type="Int32" />
</InsertParameters>
DAL FILE:
[DataObjectMethod(DataObjectMethodType.Insert)]
public static int InsertMain(int Quantity)/
{
SqlConnection con = new SqlConnection(GetConnectionString());
string strQuery = "INSERT INTO t_Main (Quantity) VALUES (#Quantity)";
SqlCommand cmd = new SqlCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Quantity", Quantity);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
CODE BEHIND FILE:
protected void btnSaveAnalysis_Click(object sender, EventArgs e)
{
odsMain.InsertParameters.Clear();
//Store parameters with values to the collection
odsMain.InsertParameters.Add(new Parameter ("Quantity", TypeCode.Int32, iQuantity.ToString()));
//Diferent ways that I tried. Still not working
//odsMain.InsertParameters.Add("Quantity", iQuantity.ToString());
//odsMain.InsertParameters["Quantity"].DefaultValue = iQuantity.ToString();
odsMain.Insert();
}
you could try like this....
ObjectDataSource for InsertParameter looks like below one
<InsertParameters>
<asp:Parameter Name="FirstName" />
<asp:Parameter Name="MiddleName" />
<asp:Parameter Name="LastName" />
<asp:Parameter Name="Desgination" />
<asp:Parameter Name="Address" />
<asp:Parameter Name="City" />
<asp:Parameter Name="State" />
<asp:Parameter Name="Country" />
</InsertParameters>
I will also pass InsertMethod property of ObjectDataSource,which will have an InsertCustomer method.
InsertCustomer method looks like below one :-
public void InsertCustomer(string FirstName, string MiddleName,string LastName, string Desgination, string Address, string City, string State, string Country)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("InsertCustomer", con);
cmd.CommandType = CommandType.StoredProcedure;
//this check is necessary, when u don't pass any value as it will pass as [default] and will give error
if (string.IsNullOrEmpty(FirstName))
FirstName = string.Empty;
if (string.IsNullOrEmpty(LastName))
LastName = string.Empty;
if (string.IsNullOrEmpty(MiddleName))
MiddleName = string.Empty;
if (string.IsNullOrEmpty(Desgination))
Desgination = string.Empty;
if (string.IsNullOrEmpty(Address))
Address = string.Empty;
if (string.IsNullOrEmpty(City))
City = string.Empty;
if (string.IsNullOrEmpty(State))
State = string.Empty;
if (string.IsNullOrEmpty(Country))
Country = string.Empty;
cmd.Parameters.AddWithValue("#IV_FirstName", FirstName);
cmd.Parameters.AddWithValue("#IV_LastName", LastName);
cmd.Parameters.AddWithValue("#IV_MiddleName", MiddleName);
cmd.Parameters.AddWithValue("#IV_Desgination", Desgination);
cmd.Parameters.AddWithValue("#IV_Address", Address);
cmd.Parameters.AddWithValue("#IV_City", City);
cmd.Parameters.AddWithValue("#IV_State", State);
cmd.Parameters.AddWithValue("#IV_Country", Country);
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
Button Save for inserting record.
//Insert record Save Button
protected void btnSave_Click(object sender, EventArgs e)
{
Customer.InsertParameters["FirstName"].DefaultValue = GetGridTextBoxValue("txtFirstName");
Customer.InsertParameters["MiddleName"].DefaultValue = GetGridTextBoxValue("txtMiddleName");
Customer.InsertParameters["LastName"].DefaultValue = GetGridTextBoxValue("txtLastName");
Customer.InsertParameters["Desgination"].DefaultValue= GetGridTextBoxValue("txtDesgination");
Customer.InsertParameters["Address"].DefaultValue = GetGridTextBoxValue("txtAddress");
Customer.InsertParameters["City"].DefaultValue = GetGridTextBoxValue("txtCity");
Customer.InsertParameters["State"].DefaultValue = GetGridTextBoxValue("txtState");
Customer.InsertParameters["Country"].DefaultValue = GetGridTextBoxValue("txtCountry");
Customer.Insert();
}
GetGridTextBoxValue function will get TextBox text value from footer row of respective column.
//Get TextBox value of GridView Footer Row
public string GetGridTextBoxValue(string txtID)
{
try
{
TextBox txt = (TextBox)gvCustomer.FooterRow.FindControl(txtID); // here you can place any text box value on your design page
return txt.Text;
}
catch (Exception ex)
{
return string.Empty;
throw ex;
}
}
and the results image is like this ...

C# Sending GridViews/DataTables via Email

I'm trying the find the best way to send a GridView or DataTable in an email.
Page Behind Code:
protected void Page_Load(object sender, EventArgs e)
{
DataTable s1 = Sql.specificReportData(Convert.ToInt32(Session["userID"]));
this.gv.DataSource = s1.DefaultView;
this.gv.DataBind();
}
This generates and binds the data successfully, but if I try and add the contents of gv to a HTML encoded email then the gv part of the email is blank. Do I need to alter the GridView so it's HTML compliant? I can't find an example of how to do this. Any help appreciated.
edit: Gave answer to Solairaya as he gave fuller example, as well as object flushing and disposal. Marked both answers up as they both helped
Page behind code
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = getHTML(GridView1);
}
private string getHTML(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter textwriter = new StringWriter(sb);
HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);
gv.RenderControl(htmlwriter);
htmlwriter.Flush();
textwriter.Flush();
htmlwriter.Dispose();
textwriter.Dispose();
return sb.ToString();
}
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
Page code
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT [UserID], [Name], [Email] FROM [WEB_Users] WHERE ([Name] LIKE '%' + #Name + '%')">
<SelectParameters>
<asp:Parameter DefaultValue="%Moha%" Name="Name" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
</form>
Hai alex try this,
Try this (C#):
using System.IO;
using System.Text;
using System.Net.Mail;
private string GridViewToHtml(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
protected void SendMailButton_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.Body = GridViewToHtml(GridView1);
mail.IsBodyHtml = true;
......
}
public override void VerifyRenderingInServerForm(Control control)
{
}