Search Results

Search found 52 results on 3 pages for 'rowtype'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • How to check the status (True/False) in a grid view on rowdatabound event?

    - by NayeemKhan
    Hi all, I have a table with three columns (ProdID,ProdName,Status). I m fetching that into a dataSet and binding that to my gridview. I have a very basic and simple rowdatabound event like this : protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.Cells[2].Text == "False") { e.Row.BackColor = System.Drawing.Color.PaleVioletRed; } } } But when i see my 3rd column (Status), it is converted to a checkbox, may be becz its containing only 'True' or 'False'. Also in my if condition : if (e.Row.Cells[3].Text == "False") the text value is showing this : "" Can anybody suggest me, how can i compare my status against True or False in my if condition.

    Read the article

  • a value that shows in select mode disappears in edit mode from a gridview column

    - by Jbob Johan
    i have a gridview(GridView1) with a few Bound Fields first one is Date (ActivityDate) from a table named "tblTime" i have managed to add one extra colum (manually), that is not bound that shows dayInWeek value according to the "ActivityDate" field programtically in CodeBehind but when i enter into Edit Mode , all Bound fields are showing their values correctly but the one column i have added manually will not show the value as it did in "select mode"(first mode b4 trying to edit) while im not a great dibbagger i have manged to view the cell's value (GridView1.Rows[e.NewEditIndex].Cells[1].Text) which does hold on to the day in week value but it does not appear in gridview edit mode only this is some of the code protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { e.Row.Cells[0].Text = "?????"; //Activity Date (in hebrew) e.Row.Cells[1].Text = "??? ?????"; //DayinWeek e.Row.Cells[2].Text = "??????"; //ActivityType (work seek vacation) named Reason e.Row.Cells[3].Text = "??? ?????"; //time finish (to Work) e.Row.Cells[4].Text = "??? ?????"; //Time out (of work) } if (e.Row.RowType == DataControlRowType.DataRow) { if (Convert.ToBoolean(ViewState["theSubIsclckd"]) == true) //if submit button clicked { try { string twekday1 = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ActiveDate")); twekday1 = twekday1.Remove(9, 11); //geting date only without the time- portion string[] arymd = twekday1.Split('/'); // spliting [d m y] in order to make int day = Convert.ToInt32(arymd[1]); // it into [m d y] ...also requierd int month = Convert.ToInt32(arymd[0]); // when i update the table int year = Convert.ToInt32(arymd[2]); DateTime ILDateInit = new DateTime(year, month, day); //finally extracting Day CultureInfo ILci = CultureInfo.CreateSpecificCulture("he-IL"); // in week //from the converted activity date string MyIL_DayInWeek = ILDateInit.ToString("dddd", ILci); ViewState["MyIL_DayInWeek"] = MyIL_DayInWeek; e.Row.Cells[1].Text = MyIL_DayInWeek; string displayReason = DataBinder.Eval(e.Row.DataItem, "Reason").ToString(); e.Row.Cells[2].Text = displayReason; } catch (System.Exception excep) { Js.functions.but bb = new Js.functions.but(); bb.buttonName = "rex"; bb.documentwrite = true; bb.testCsVar = excep.ToString(); bb.f1(bb); // this was supposed to throw exep in javaScript injected from code behid - alert } // just in case.. } } so that works for the non edit period of time then when i hit the edit ... no day in week shows THE aspX - after selcting date... name etc' , click on button to display gridview: <asp:Button ID="TheSubB" runat="server" Text="???" onclick="TheSubB_Click" /> <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" onrowediting="GridView1_RowEditing" onrowcancelingedit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" AutoGenerateColumns="False" DataKeyNames="tId" DataSourceID="SqlDataSource1" style="z-index: 1; left: 0%; top: 0%; position: relative; width: 812px; height: 59px; font-family:Arial; text-align: center;" AllowSorting="True" > <AlternatingRowStyle BackColor="PaleGoldenrod" /> <Columns> <asp:BoundField DataField="ActiveDate" HeaderText="ActiveDate" SortExpression="ActiveDate" ControlStyle-Width="70" DataFormatString="{0:dd/MM/yyyy}" > <ControlStyle Width="70px" /> </asp:BoundField> <asp:TemplateField HeaderText="???.???.??"> <EditItemTemplate> <asp:TextBox ID="dayinW_EditTB" runat="server"></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="dayInW_editLabel" runat="server"></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Reason" HeaderText="???? ?????" SortExpression="Reason" ControlStyle-Width="50"> <ControlStyle Width="50px" /> </asp:BoundField> <asp:BoundField DataField="TimeOut" HeaderText="TimeOut" SortExpression="TimeOut" ControlStyle-Width="50" DataFormatString="{0:HH:mm}" > <ControlStyle Width="50px"></ControlStyle> </asp:BoundField> <asp:BoundField DataField="TimeIn" HeaderText="TimeIn" SortExpression="TimeIn" ControlStyle-Width="50" DataFormatString="{0:HH:mm}" > <ControlStyle Width="50px"></ControlStyle> </asp:BoundField> <asp:TemplateField HeaderText="????" > <EditItemTemplate> <asp:ImageButton width="15" Height="15" ImageUrl="~/images/edit.png" runat="server" CausesValidation="True" CommandName="Update" Text="Update"> </asp:ImageButton> <asp:ImageButton Width="15" Height="15" ImageUrl="images/cancel.png" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"> </asp:ImageButton> </EditItemTemplate> <ItemTemplate> <asp:ImageButton width="25" Height="15" ImageUrl="images/edit.png" ID="EditIB" runat="server" CausesValidation="False" CommandName="Edit" AlternateText="????"></asp:ImageButton> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="???"> <ItemTemplate> <asp:ImageButton width="15" Height="15" ImageUrl="images/Delete.png" ID="DeleteIB" runat="server" CommandName="Delete" AlternateText="???" /> </ItemTemplate> </asp:TemplateField> </Columns> <FooterStyle BackColor="Tan" /> <HeaderStyle BackColor="Tan" Font-Bold="True" /> <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" /> <SortedAscendingCellStyle BackColor="#FAFAE7" /> <SortedAscendingHeaderStyle BackColor="#DAC09E" /> <SortedDescendingCellStyle BackColor="#E1DB9C" /> <SortedDescendingHeaderStyle BackColor="#C2A47B" /> </asp:GridView>

    Read the article

  • Manual (Dynamic) LINQ subquery using IN clause

    - by immortalali-msn-com
    Hi Everyone, I want to query the DB through LINQ writing manual SQL, my linq method is: var q = db.TableView.Where(sqlAfterWhere); returnValue = q.Count(); this method queries well if the value passed to variable "sqlAfterWhere" is: (this variable is String type) it.Name = 'xyz' but what if i want to use IN clause, using a sub query. (i need to use 'it' before every column name in the above query to work), i cant use 'it' before the sub query columns as its a separate query, so what should i do, if i dont use any thing, and use column names directly it gives error saying " could not be resolved" where is my column names with out 'it' at the begining. So the query not working is: (this is a string passed to the variable above): it.Name IN (SELECT Name FROM TableName WHERE Address LIKE '%SomeAddress%') the errors come out as: Name could not be resolved Address could not be resolved The exact error is: "'Name' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly., near simple identifier, line 6, column 25." Same error for "Address as well if i use 'it.' before these columns it gives error as: "The element type 'Edm.Int32' and the CollectionType 'Transient.collection[Transient.rowtype(GroupID,Edm.Int32(Nullable=True,DefaultValue=))]' are not compatible. The IN expression only supports entity, primitive, and reference types. , near WHERE predicate, line 6, column 14." Thanks for the help

    Read the article

  • Getting gridview column value as parameter for javascript function

    - by newName
    I have a gridview with certain number of columns and the ID column where I want to get the value from is currently set to visible = false. The other column is a TemplateField column (LinkButton) and as the user clicks on the button it will grab the value from the ID column and pass the value to one of my javascript function. WebForm: <script language=javascript> function openContent(contentID) { window.open('myContentPage.aspx?contentID=' + contentID , 'View Content','left=300,top=300,toolbar=no,scrollbars=yes,width=1000,height=500'); return false; } </script> <asp:GridView ID="gvCourse" runat="server" AutoGenerateColumns="False" OnRowCommand="gvCourse_RowCommand" OnRowDataBound="gvCourse_RowDataBound" BorderStyle="None" GridLines="None"> <RowStyle BorderStyle="None" /> <Columns> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lnkContent" runat="server" CommandName="View" CommandArgument='<%#Eval("contentID") %>' Text='<%#Eval("contentName") %>'> </asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="contentID" HeaderText="contentID" ReadOnly="True" SortExpression="contentID" Visible="False" /> <asp:BoundField DataField="ContentName" HeaderText="ContentName" ReadOnly="True" SortExpression="ContentName" Visible="False" /> </Columns> <AlternatingRowStyle BorderStyle="None" /> Code behind: protected void gvCourse_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "View") { intID = Convert.ToInt32(e.CommandArgument); } } protected void gvCourse_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ((LinkButton)e.Row.FindControl("lnkContent")).Attributes.Add("onclick", "return openContent('" + intID + "');"); } } right not i'm trying to get the intID based on user selected item so when the user clicks on the linkbutton it will open a popup window using javascript and the ID will be used as querystring.

    Read the article

  • Improving Performance of Crystal Reports using Stored Procedures

    - by mjh41
    Recently I updated a Crystal Report that was doing all of its work on the client-side (Selects, formulas, etc) and changed all of the logic to be done on the server-side through Stored Procedures using an Oracle 11g database. Now the report is only being used to display the output of the stored procedures and nothing else. Everything I have read on this subject says that utilizing stored procedures should greatly reduce the running time of the report, but it still takes roughly the same amount of time to retrieve the data from the server. Is there something wrong with the stored procedure I have written, or is the issue in the Crystal Report itself? Here is the stored procedure code along with the package that defines the necessary REF CURSOR. CREATE OR REPLACE PROCEDURE SP90_INVENTORYDATA_ALL ( invdata_cur IN OUT sftnecm.inv_data_all_pkg.inv_data_all_type, dCurrentEndDate IN vw_METADATA.CASEENTRCVDDATE%type, dCurrentStartDate IN vw_METADATA.CASEENTRCVDDATE%type ) AS BEGIN OPEN invdata_cur FOR SELECT vw_METADATA.CREATIONTIME, vw_METADATA.RESRESOLUTIONDATE, vw_METADATA.CASEENTRCVDDATE, vw_METADATA.CASESTATUS, vw_METADATA.CASENUMBER, (CASE WHEN vw_METADATA.CASEENTRCVDDATE < dCurrentStartDate AND ( (vw_METADATA.CASESTATUS is null OR vw_METADATA.CASESTATUS != 'Closed') OR TO_DATE(vw_METADATA.RESRESOLUTIONDATE, 'MM/DD/YYYY') >= dCurrentStartDate) then 1 else 0 end) InventoryBegin, (CASE WHEN (to_date(vw_METADATA.RESRESOLUTIONDATE, 'MM/DD/YYYY') BETWEEN dCurrentStartDate AND dCurrentEndDate) AND vw_METADATA.RESRESOLUTIONDATE is not null AND vw_METADATA.CASESTATUS is not null then 1 else 0 end) CaseClosed, (CASE WHEN vw_METADATA.CASEENTRCVDDATE BETWEEN dCurrentStartDate AND dCurrentEndDate then 1 else 0 end) CaseCreated FROM vw_METADATA WHERE vw_METADATA.CASEENTRCVDDATE <= dCurrentEndDate ORDER BY vw_METADATA.CREATIONTIME, vw_METADATA.CASESTATUS; END SP90_INVENTORYDATA_ALL; And the package: CREATE OR REPLACE PACKAGE inv_data_all_pkg AS TYPE inv_data_all_type IS REF CURSOR RETURN inv_data_all_temp%ROWTYPE; END inv_data_all_pkg;

    Read the article

  • PLPGSQL : How to return a record from function executed by INSERT/UPDATE rule?

    - by seas
    Do the following scheme for my database: create sequence data_sequence; create table data_table { id integer primary key; field varchar(100); }; create view data_view as select id, field from data_table; create function data_insert(_new data_view) returns data_view as $$declare _id integer; _result data_view%rowtype; begin _id := nextval('data_sequence'); insert into data_table(id, field) values(_id, _new.field); select * into _result from data_view where id = _id; return _result; end; $$ language plpgsql; create rule insert as on insert to data_view do instead select data_insert(new); Then type in psql: insert into data_view(field) values('abc'); Would like to see something like: id | field ----+--------- 1 | abc Instead see: data_insert ------------- (1, "abc") Is it possible to fix this somehow? Thanks for any ideas. Ultimate idea is to use this in other functions, so that I could obtain id of just inserted record without selecting for it from scratch. Something like: insert into data_view(field) values('abc') returning id into my_variable would be nice but doesn't work with error: ERROR: cannot perform INSERT RETURNING on relation "data_view" HINT: You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause. I don't really understand that HINT. I use PostgreSQL 8.4.

    Read the article

  • Trouble with LINQ databind to GridView and RowDataBound

    - by Michael
    Greetings all, I am working on redesigning my personal Web site using VS 2008 and have chosen to use LINQ to create by data-access layer. Part of my site will be a little app to help manage my budget better. My first LINQ query does successfully execute and display in a GridView, but when I try to use a RowDataBound event to work with the results and refine them a bit, I get the error: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) This interesting part is, if I just try to put in a var s = "s"; anywhere else in the same file, I get the same error too. If I go to other files in the web project, var s = "s"; compiles fine. Here is the LINQ Query call: public static IQueryable pubGetRecentTransactions(int param_accountid) { clsDataContext db; db = new clsDataContext(); var query = from d in db.tblMoneyTransactions join p in db.tblMoneyTransactions on d.iParentTransID equals p.iTransID into dp from p in dp.DefaultIfEmpty() where d.iAccountID == param_accountid orderby d.dtTransDate descending, d.iTransID ascending select new { d.iTransID, d.dtTransDate, sTransDesc = p != null ? p.sTransDesc : d.sTransDesc, d.sTransMemo, d.mTransAmt, d.iCheckNum, d.iParentTransID, d.iReconciled, d.bIsTransfer }; return query; } protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { this.prvLoadData(); } } internal void prvLoadData() { prvCtlGridTransactions.DataSource = clsMoneyTransactions.pubGetRecentTransactions(2); prvCtlGridTransactions.DataBind(); } protected void prvCtlGridTransactions_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var datarow = e.Row.DataItem; var s = "s"; e.Row.Cells[0].Text = datarow.dtTransDate.ToShortDateString(); e.Row.Cells[1].Text = datarow.sTransDesc; e.Row.Cells[2].Text = datarow.mTransAmt.ToString("c"); e.Row.Cells[3].Text = datarow.iReconciled.ToString(); }//end if }//end RowDataBound My googling to date hasn't found a good answer, so I turn it over to this trusted community. I appreciate your time in assisting me.

    Read the article

  • adding header row to gridview won't allow you to save the last item row

    - by Lex
    I've modified my GridView to have an extra Header row, however that extra row has caused my grid view row count to be incorrect. Basically, when I want to save the Gridview now, it doesn't recognize the last item line. In my current test I have 5 Item Lines, however only 4 of them are being saved. My code for creating the additional header Line: protected void gvStatusReport_RowDataBound(object sender, GridViewRowEventArgs e) { // This grid has multiple rows, fake the top row. if (e.Row.RowType == DataControlRowType.Header) { SortedList FormatCells = new SortedList(); FormatCells.Add("1", ",6,1"); FormatCells.Add("2", "Time Spent,7,1"); FormatCells.Add("3", "Total,2,1"); FormatCells.Add("4", ",6,1"); GetMultiRowHeader(e, FormatCells); } } The function to create a new row: public void GetMultiRowHeader(GridViewRowEventArgs e, SortedList GetCels) { GridViewRow row; IDictionaryEnumerator enumCels = GetCels.GetEnumerator(); row = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal); while (enumCels.MoveNext()) { string[] count = enumCels.Value.ToString().Split(Convert.ToChar(",")); TableCell cell = new TableCell(); cell.RowSpan = Convert.ToInt16(count[2].ToString()); cell.ColumnSpan = Convert.ToInt16(count[1].ToString()); cell.Controls.Add(new LiteralControl(count[0].ToString())); cell.HorizontalAlign = HorizontalAlign.Center; row.Cells.Add(cell); } e.Row.Parent.Controls.AddAt(0, row); } Then when I'm going to save, I loop through the rows: int totalRows = gvStatusReport.Rows.Count; for (int rowNumber = 0; rowNumber < totalRows; rowNumber++) { However the first line doesn't seem to have any of the columns that the item row has, and the last line doesn't even show up. My problem is that I do need the extra header line, but what is the best way to fix this?

    Read the article

  • Can I programmatically add a linkbutton to gridview?

    - by pschorf
    I've been looking through some similar questions without any luck. What I'd like to do is have a gridview which for certain items shows a linkbutton and for other items shows a hyperlink. This is the code I currently have: public void gv_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var data = (FileDirectoryInfo)e.Row.DataItem; var img = new System.Web.UI.HtmlControls.HtmlImage(); if (data.Length == null) { img.Src = "/images/folder.jpg"; var lnk = new LinkButton(); lnk.ID = "lnkFolder"; lnk.Text = data.Name; lnk.Command += new CommandEventHandler(changeFolder_OnCommand); lnk.CommandArgument = data.Name; e.Row.Cells[0].Controls.Add(lnk); } else { var lnk = new HyperLink(); lnk.Text = data.Name; lnk.Target = "_blank"; lnk.NavigateUrl = getLink(data.Name); e.Row.Cells[0].Controls.Add(lnk); img.Src = "/images/file.jpg"; } e.Row.Cells[0].Controls.AddAt(0, img); } } where the first cell is a TemplateField. Currently, everything displays correctly, but the linkbuttons don't raise the Command event handler, and all of the controls disappear on postback. Any ideas?

    Read the article

  • PL/PGSQL function, having trouble accessing a returned result set from psycopg2...

    - by Paul
    I have this pl/pgsql function: CREATE OR REPLACE FUNCTION get_result(id integer) RETURNS SETOF my_table AS $ DECLARE result_set my_table%ROWTYPE; BEGIN IF id=0 THEN SELECT INTO result_set my_table_id, my_table_value FROM my_table; ELSE SELECT INTO result_set my_table_id, my_table_value FROM my_table WHERE my_table_id=id; END IF; RETURN; END; $ LANGUAGE plpgsql; I am trying to use this with Python's psycopg2 library. Here is the python code: import psycopg2 as pg conn = pg.connect(host='myhost', database='mydatabase', user='user', password='passwd') cur = conn.cursor() return cur.execute("SELECT * FROM get_result(0);") # returns NoneType However, if i just do the regular query, I get the correct set of rows back: ... return cur.execute("SELECT my_table_id, my_table_value FROM mytable;") # returns iterable result set Theres obviously something wrong with my pl/pgsql function, but I can't seem to get it right. I also tried using RETURN result_set; instead of just RETURN in the 10th line of my plpgsql function, but got an error from postgres.

    Read the article

  • How to return a record from function executed by INSERT/UPDATE rule?

    - by seas
    Do the following scheme for my database: create sequence data_sequence; create table data_table { id integer primary key; field varchar(100); }; create view data_view as select id, field from data_table; create function data_insert(_new data_view) returns data_view as $$declare _id integer; _result data_view%rowtype; begin _id := nextval('data_sequence'); insert into data_table(id, field) values(_id, _new.field); select * into _result from data_view where id = _id; return _result; end; $$ language plpgsql; create rule insert as on insert to data_view do instead select data_insert(new); Then type in psql: insert into data_view(field) values('abc'); Would like to see something like: id | field ----+--------- 1 | abc Instead see: data_insert ------------- (1, "abc") Is it possible to fix this somehow? Thanks for any ideas. Ultimate idea is to use this in other functions, so that I could obtain id of just inserted record without selecting for it from scratch. Something like: insert into data_view(field) values('abc') returning id into my_variable would be nice but doesn't work with error: ERROR: cannot perform INSERT RETURNING on relation "data_view" HINT: You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause. I don't really understand that HINT. I use PostgreSQL 8.4.

    Read the article

  • confusion about using types instead of gtts in oracle

    - by Omnipresent
    I am trying to convert queries like below to types so that I won't have to use GTT: insert into my_gtt_table_1 (house, lname, fname, MI, fullname, dob) (select house, lname, fname, MI, fullname, dob from (select 'REG' house, mbr_last_name lname, mbr_first_name fname, mbr_mi MI, mbr_first_name || mbr_mi || mbr_last_name fullname, mbr_dob dob from table_1 a, table_b where a.head = b.head and mbr_number = '01' and mbr_last_name = v_last_name) c above is just a sample but complex queries are bigger than this. the above is inside a stored procedure. So to avoid the gtt (my_gtt_table_1). I did the following: create or replace type lname_row as object ( house varchar2(30) lname varchar2(30), fname varchar2(30), MI char(1), fullname VARCHAR2(63), dob DATE ) create or replace type lname_exact as table of lname_row Now in the SP: type lname_exact is table of <what_table_should_i_put_here>%rowtype; tab_a_recs lname_exact; In the above I am not sure what table to put as my query has nested subqueries. query in the SP: (I am trying this for sample purpose to see if it works) select lname_row('', '', '', '', '', '', sysdate) bulk collect into tab_a_recs from table_1; I am getting errors like : ORA-00913: too many values I am really confused and stuck with this :(

    Read the article

  • How to return a record from function, executed by INSERT/UPDATE rule (trigger)?

    - by seas
    Do the following scheme for my database: create sequence data_sequence; create table data_table { id integer primary key; field varchar(100); }; create view data_view as select id, field from data_table; create function data_insert(_new data_view) returns data_view as $$declare _id integer; _result data_view%rowtype; begin _id := nextval('data_sequence'); insert into data_table(id, field) values(_id, _new.field); select * into _result from data_view where id = _id; return _result; end; $$ language plpgsql; create rule insert as on insert to data_view do instead select data_insert(new); Then type in psql: insert into data_view(field) values('abc'); Would like to see something like: id | field ----+--------- 1 | abc Instead see: data_insert ------------- (1, "abc") Is it possible to fix this somehow? Thanks for any ideas. Ultimate idea is to use this in other functions, so that I could obtain id of just inserted record without selecting for it from scratch. Something like: insert into data_view(field) values('abc') returning id into my_variable would be nice but doesn't work with error: ERROR: cannot perform INSERT RETURNING on relation "data_view" HINT: You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause. I don't really understand that HINT. I use PostgreSQL 8.4.

    Read the article

  • ArgumentOutOfRangeException was unhandled by user code - (ASP .net)

    - by ASr..
    I use a GridView to display the records from the database. Also i've attached a Hyperlink to the GridView using TemplateField. When I try to add "onclick" attribute to the HyperLink inside the RowDateBound event, I get the following error.. GridView1.DataKeys[e.Row.RowIndex].Value = 'GridView1.DataKeys[e.Row.RowIndex]' threw an exception of type 'System.ArgumentOutOfRangeException' Message = "Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index" This is the coding inside the RowDataBound mentod.. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { HyperLink HyperLink1 = (HyperLink)e.Row.FindControl("HyperLink1"); //The following line makes the error HyperLink1.Attributes.Add("onclick", "ShowMyModalPopup('" + GridView1.DataKeys[e.Row.RowIndex].Value + "')"); } } This is "ShowMyModalPopup" function in javascript <script type="text/javascript"> function ShowMyModalPopup(userpk) { var modal = $find('ModalPopupExtender1'); modal.show(); WebService.FetchOneUser(userpk,DisplayResult); } </script> Can anyone please explain me why this error occurs.. Many thanks in advance..

    Read the article

  • Cast exception being generated when using the same type of object

    - by David Tunnell
    I was previously using static variables to hold variable data that I want to save between postbacks. I was having problems and found that the data in these variables is lost when the appdomain ends. So I did some research and decided to go with ViewStates: static Dictionary<string, linkButtonObject> linkButtonDictonary; protected void Page_Load(object sender, EventArgs e) { if (ViewState["linkButtonDictonary"] != null) { linkButtonDictonary = (Dictionary<string, linkButtonObject>)ViewState["linkButtonDictonary"]; } else { linkButtonDictonary = new Dictionary<string, linkButtonObject>(); } } And here is the very simple class I use: [Serializable] public class linkButtonObject { public string storyNumber { get; set; } public string TaskName { get; set; } } I am adding to linkButtonDictionary as a gridview is databound: protected void hoursReportGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton btn = (LinkButton)e.Row.FindControl("taskLinkButton"); linkButtonObject currentRow = new linkButtonObject(); currentRow.storyNumber = e.Row.Cells[3].Text; currentRow.TaskName = e.Row.Cells[5].Text; linkButtonDictonary.Add(btn.UniqueID, currentRow); } } It appears that my previous issues are resolved however a new one has arisin. Sometime when I postback I am getting this error: [A]System.Collections.Generic.Dictionary2[System.String,linkButtonObject] cannot be cast to [B]System.Collections.Generic.Dictionary2[System.String,linkButtonObject]. Type A originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. Type B originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. I don't understand how there can be a casting issue when I am using the same class everywhere. What am I doing wrong and how do I fix it?

    Read the article

  • Inserting and Deleting Sub Rows in GridView

    - by Vincent Maverick Durano
    A user in the forums (http://forums.asp.net) is asking how to insert  sub rows in GridView and also add delete functionality for the inserted sub rows. In this post I'm going to demonstrate how to this in ASP.NET WebForms.  The basic idea to achieve this is we just need to insert row data in the DataSource that is being used in GridView since the GridView rows will be generated based on the DataSource data. To make it more clear then let's build up a sample application. To start fire up Visual Studio and create a WebSite or Web Application project and then add a new WebForm. In the WebForm ASPX page add this GridView markup below:   1: <asp:gridview ID="GridView1" runat="server" AutoGenerateColumns="false" onrowdatabound="GridView1_RowDataBound"> 2: <Columns> 3: <asp:BoundField DataField="RowNumber" HeaderText="Row Number" /> 4: <asp:TemplateField HeaderText="Header 1"> 5: <ItemTemplate> 6: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 7: </ItemTemplate> 8: </asp:TemplateField> 9: <asp:TemplateField HeaderText="Header 2"> 10: <ItemTemplate> 11: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 12: </ItemTemplate> 13: </asp:TemplateField> 14: <asp:TemplateField HeaderText="Header 3"> 15: <ItemTemplate> 16: <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> 17: </ItemTemplate> 18: </asp:TemplateField> 19: <asp:TemplateField HeaderText="Action"> 20: <ItemTemplate> 21: <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click" Text="Insert"></asp:LinkButton> 22: </ItemTemplate> 23: </asp:TemplateField> 24: </Columns> 25: </asp:gridview>   Then at the code behind source of ASPX page you can add this codes below:   1: private DataTable FillData() { 2:   3: DataTable dt = new DataTable(); 4: DataRow dr = null; 5:   6: //Create DataTable columns 7: dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); 8:   9: //Create Row for each columns 10: dr = dt.NewRow(); 11: dr["RowNumber"] = 1; 12: dt.Rows.Add(dr); 13:   14: dr = dt.NewRow(); 15: dr["RowNumber"] = 2; 16: dt.Rows.Add(dr); 17:   18: dr = dt.NewRow(); 19: dr["RowNumber"] = 3; 20: dt.Rows.Add(dr); 21:   22: dr = dt.NewRow(); 23: dr["RowNumber"] = 4; 24: dt.Rows.Add(dr); 25:   26: dr = dt.NewRow(); 27: dr["RowNumber"] = 5; 28: dt.Rows.Add(dr); 29:   30: //Store the DataTable in ViewState for future reference 31: ViewState["CurrentTable"] = dt; 32:   33: return dt; 34:   35: } 36:   37: private void BindGridView(DataTable dtSource) { 38: GridView1.DataSource = dtSource; 39: GridView1.DataBind(); 40: } 41:   42: private DataRow InsertRow(DataTable dtSource, string value) { 43: DataRow dr = dtSource.NewRow(); 44: dr["RowNumber"] = value; 45: return dr; 46: } 47: //private DataRow DeleteRow(DataTable dtSource, 48:   49: protected void Page_Load(object sender, EventArgs e) { 50: if (!IsPostBack) { 51: BindGridView(FillData()); 52: } 53: } 54:   55: protected void LinkButton1_Click(object sender, EventArgs e) { 56: LinkButton lb = (LinkButton)sender; 57: GridViewRow row = (GridViewRow)lb.NamingContainer; 58: DataTable dtCurrentData = (DataTable)ViewState["CurrentTable"]; 59: if (lb.Text == "Insert") { 60: //Insert new row below the selected row 61: dtCurrentData.Rows.InsertAt(InsertRow(dtCurrentData, row.Cells[0].Text + "-sub"), row.RowIndex + 1); 62:   63: } 64: else { 65: //Delete selected sub row 66: dtCurrentData.Rows.RemoveAt(row.RowIndex); 67: } 68:   69: BindGridView(dtCurrentData); 70: ViewState["CurrentTable"] = dtCurrentData; 71: } 72:   73: protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { 74: if (e.Row.RowType == DataControlRowType.DataRow) { 75: if (e.Row.Cells[0].Text.Contains("-sub")) { 76: ((LinkButton)e.Row.FindControl("LinkButton1")).Text = "Delete"; 77: } 78: } 79: }   As you can see the code above is pretty straight forward and self explainatory but just to give you a short explaination the code above is composed of three (3) private methods which are the FillData(), BindGridView and InsertRow(). The FillData() method is a method that returns a DataTable and basically creates a dummy data in the DataTable to be used as the GridView DataSource. You can replace the code in that method if you want to use actual data from database but for the purpose of this example I just fill the DataTable with a dummy data on it. The BindGridVew is a method that handles the actual binding of GridVew. The InsertRow() is a method that returns a DataRow. This method handles the insertion of the sub row. Now in the LinkButton OnClick event, we casted the sender to a LinkButton to determine the specific object that fires up the event and get the row values. We then reference the Data from ViewState to get the current data that is being used in the GridView. If the LinkButton text is "Insert" then we will insert new row to the DataSource ( in this case the DataTable) based on the rowIndex if not then Delete the sub row that was added. Here are some screen shots of the output below: On initial load:   After inserting a sub row:   That's it! I hope someone find this post useful!   Technorati Tags: ASP.NET,C#,GridView

    Read the article

  • Extending QuickBooks Reporting with the QuickBooks ADO.NET Data Provider

    - by dataintegration
    The ADO.NET Provider for QuickBooks comes with several reports you may request from QuickBooks by default. However, there are many more that are not readily available. The ADO.NET Provider for QuickBooks makes it easy for you to create new reports and customize existing ones. In this article, we will illustrate how to create your own report and retrieve it from the Server Explorer in Visual Studio. For this example we will show how to create an Item Profitability Report. Creating the report script file Step 1: Download the sample reports available here. Extract them to a folder of your choice. Step 2: Make a copy of the ReportGeneralSummary.rsd file and rename it to ItemProfitability.rsd. Then open the file in any text editor. Step 3: Open the installation directory of the ADO.NET Provider for QuickBooks. Under the \db\ folder, locate the ReportJob.rsb file. Open this file in another text editor. Note: Although we are using ReportJob.rsb for this example, other reports may be contained in other Report*.rsb files. We recommend consulting the included help file and first locating the Report stored procedure and ReportType you are looking for. Otherwise, you may open each Report*.rsb file and look under the "reporttype" input for the report you are attempting to create. Step 4: First, let's rename the title of ItemProfitability.rsd. Near the top of the file you will see a title and description. Change the title to match the name of the file. Change the description to anything you like. For example: <rsb:info title="ItemProfitability" description="Executes my custom report."> Just below the Title, there are a number of columns. The Id represents the row number. The RowType represents the type of data returned by QuickBooks. The ColumnValue* columns represent all of the column data returned by QuickBooks. In some instances, we may need to add additional ColumnValue columns. Step 5: To add additional ColumnValue columns, simply copy the last column, paste it directly below, and continue increasing the numerical value at end of the attribute name. For example: <attr name="ColumnValue9" xs:type="string" readonly="true" required="false" desc="Represents a column of data."/> <attr name="ColumnValue10" xs:type="string" readonly="true" required="false" desc="Represents a column of data."/> <attr name="ColumnValue11" xs:type="string" readonly="true" required="false" desc="Represents a column of data."/> <attr name="ColumnValue12" xs:type="string" readonly="true" required="false" desc="Represents a column of data."/> ... Caution: Do not rename the ColumnValue* definitions themselves. They are generalized so that we can understand each type of report returned by QuickBooks. Renaming them to something other than ColumnValue* will cause your columns to return with null values. Step 6: Now let's update the available inputs for the table. From the ReportJob.rsb file, copy all of the input elements into ItemProfitability under the "Psuedo-Column definitions" comment. You will be replacing the existing input elements in ItemProfitability with inputs from ReportJob. When you are done, it should look like this: <!-- Psuedo-Column definitions --> <input name="reporttype" description="The type of the report." value="ITEMESTIMATESVSACTUALS,ITEMPROFITABILITY,JOBESTIMATESVSACTUALSDETAIL,JOBESTIMATESVSACTUALSSUMMARY,JOBPROFITABILITYDETAIL,JOBPROFITABILITYSUMMARY," default="ITEMESTIMATESVSACTUALS" /> <input name="reportperiod" description="Report date range in the format (fromdate:todate), and either value may be omitted for an open ended range (e.g. 2009-12-25:). Supported date format: yyyy-MM-dd." /> <input name="reportdaterangemacro" description="Use a predefined date range." value="ALL,TODAY,THISWEEK,THISWEEKTODATE,THISMONTH,THISMONTHTODATE,THISQUARTER,THISQUARTERTODATE,THISYEAR,THISYEARTODATE,YESTERDAY,LASTWEEK,LASTWEEKTODATE,LASTMONTH,LASTMONTHTODATE,LASTQUARTER,LASTQUARTERTODATE,LASTYEAR,LASTYEARTODATE,NEXTWEEK,NEXTFOURWEEKS,NEXTMONTH,NEXTQUARTER,NEXTYEAR," default="ALL" /> ... Step 7: Now let's update the operationname attribute. This needs to match the same operationname used by ReportJob. After you have copied the correct value from ReportJob.rsb, the operationname in ItemProfitability should look like so: <rsb:set attr="operationname" value="qbReportJob"/> Step 8: There is one more thing we can do to make this a true Item Profitability report. We can remove the reporttype input and hardcode the value. To do this, copy and paste the rsb:set used for operationname. Then rename the attr and value to match the name and value you want to use. For example: <rsb:set attr="operationname" value="qbReportJob"/> <rsb:set attr="reporttype" value="ITEMPROFITABILITY"/> After this you can remove the input for reporttype. Now that you have your own report file, we can move on to displaying the report in the Visual Studio server explorer. Accessing the report through the Data Provider Step 1: Open Visual Studio. In the Server Explorer, configure a new connection with the QuickBooks Data Provider. Step 2: For the Location connection string property, enter the directory where the new report has been saved to. Step 3: The new report should appear as a new view in the Server Explorer. Let's retrieve data from it. Step 4: You can specify any inputs in the WHERE clause. New Report Example Script To help you get started using this new QuickBooks Data Provider report, you will need to download the QuickBooks ADO.NET Data Provider and the fully functional sample script.

    Read the article

  • FAQ: Highlight GridView Row on Click and Retain Selected Row on Postback

    - by Vincent Maverick Durano
    A couple of months ago I’ve written a simple demo about “Highlighting GridView Row on MouseOver”. I’ve noticed many members in the forums (http://forums.asp.net) are asking how to highlight row in GridView and retain the selected row across postbacks. So I’ve decided to write this post to demonstrate how to implement it as reference to others who might need it. In this demo I going to use a combination of plain JavaScript and jQuery to do the client-side manipulation. I presumed that you already know how to bind the grid with data because I will not include the codes for populating the GridView here. For binding the gridview you can refer this post: Binding GridView with Data the ADO.Net way or this one: GridView Custom Paging with LINQ. To get started let’s implement the highlighting of GridView row on row click and retain the selected row on postback.  For simplicity I set up the page like this: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>You have selected Row: (<asp:Label ID="Label1" runat="server" />)</h2> <asp:HiddenField ID="hfCurrentRowIndex" runat="server"></asp:HiddenField> <asp:HiddenField ID="hfParentContainer" runat="server"></asp:HiddenField> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Trigger Postback" /> <asp:GridView ID="grdCustomer" runat="server" AutoGenerateColumns="false" onrowdatabound="grdCustomer_RowDataBound"> <Columns> <asp:BoundField DataField="Company" HeaderText="Company" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="Title" HeaderText="Title" /> <asp:BoundField DataField="Address" HeaderText="Address" /> </Columns> </asp:GridView> </asp:Content>   Note: Since the action is done at the client-side, when we do a postback like (clicking on a button) the page will be re-created and you will lose the highlighted row. This is normal because the the server doesn't know anything about the client/browser not unless if you do something to notify the server that something has changed. To persist the settings we will use some HiddenFields control to store the data so that when it postback we can reference the value from there. Now here’s the JavaScript functions below: <asp:content id="Content1" runat="server" contentplaceholderid="HeadContent"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script> <script type="text/javascript">       var prevRowIndex;       function ChangeRowColor(row, rowIndex) {           var parent = document.getElementById(row);           var currentRowIndex = parseInt(rowIndex) + 1;                 if (prevRowIndex == currentRowIndex) {               return;           }           else if (prevRowIndex != null) {               parent.rows[prevRowIndex].style.backgroundColor = "#FFFFFF";           }                 parent.rows[currentRowIndex].style.backgroundColor = "#FFFFD6";                 prevRowIndex = currentRowIndex;                 $('#<%= Label1.ClientID %>').text(currentRowIndex);                 $('#<%= hfParentContainer.ClientID %>').val(row);           $('#<%= hfCurrentRowIndex.ClientID %>').val(rowIndex);       }             $(function () {           RetainSelectedRow();       });             function RetainSelectedRow() {           var parent = $('#<%= hfParentContainer.ClientID %>').val();           var currentIndex = $('#<%= hfCurrentRowIndex.ClientID %>').val();           if (parent != null) {               ChangeRowColor(parent, currentIndex);           }       }          </script> </asp:content>   The ChangeRowColor() is the function that sets the background color of the selected row. It is also where we set the previous row and rowIndex values in HiddenFields.  The $(function(){}); is a short-hand for the jQuery document.ready event. This event will be fired once the page is posted back to the server that’s why we call the function RetainSelectedRow(). The RetainSelectedRow() function is where we referenced the current selected values stored from the HiddenFields and pass these values to the ChangeRowColor() function to retain the highlighted row. Finally, here’s the code behind part: protected void grdCustomer_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onclick", string.Format("ChangeRowColor('{0}','{1}');", e.Row.ClientID, e.Row.RowIndex)); } } The code above is responsible for attaching the javascript onclick event for each row and call the ChangeRowColor() function and passing the e.Row.ClientID and e.Row.RowIndex to the function. Here’s the sample output below:   That’s it! I hope someone find this post useful! Technorati Tags: jQuery,GridView,JavaScript,TipTricks

    Read the article

  • FAQ&ndash;Highlight GridView Row on Click and Retain Selected Row on Postback

    - by Vincent Maverick Durano
    A couple of months ago I’ve written a simple demo about “Highlighting GridView Row on MouseOver”. I’ve noticed many members in the forums (http://forums.asp.net) are asking how to highlight row in GridView and retain the selected row across postbacks. So I’ve decided to write this post to demonstrate how to implement it as reference to others who might need it. In this demo I going to use a combination of plain JavaScript and jQuery to do the client-side manipulation. I presumed that you already know how to bind the grid with data because I will not include the codes for populating the GridView here. For binding the gridview you can refer this post: Binding GridView with Data the ADO.Net way or this one: GridView Custom Paging with LINQ. To get started let’s implement the highlighting of GridView row on row click and retain the selected row on postback.  For simplicity I set up the page like this: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>You have selected Row: (<asp:Label ID="Label1" runat="server" />)</h2> <asp:HiddenField ID="hfCurrentRowIndex" runat="server"></asp:HiddenField> <asp:HiddenField ID="hfParentContainer" runat="server"></asp:HiddenField> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Trigger Postback" /> <asp:GridView ID="grdCustomer" runat="server" AutoGenerateColumns="false" onrowdatabound="grdCustomer_RowDataBound"> <Columns> <asp:BoundField DataField="Company" HeaderText="Company" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="Title" HeaderText="Title" /> <asp:BoundField DataField="Address" HeaderText="Address" /> </Columns> </asp:GridView> </asp:Content>   Note: Since the action is done at the client-side, when we do a postback like (clicking on a button) the page will be re-created and you will lose the highlighted row. This is normal because the the server doesn't know anything about the client/browser not unless if you do something to notify the server that something has changed. To persist the settings we will use some HiddenFields control to store the data so that when it postback we can reference the value from there. Now here’s the JavaScript functions below: <asp:content id="Content1" runat="server" contentplaceholderid="HeadContent"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script> <script type="text/javascript">       var prevRowIndex;       function ChangeRowColor(row, rowIndex) {           var parent = document.getElementById(row);           var currentRowIndex = parseInt(rowIndex) + 1;                 if (prevRowIndex == currentRowIndex) {               return;           }           else if (prevRowIndex != null) {               parent.rows[prevRowIndex].style.backgroundColor = "#FFFFFF";           }                 parent.rows[currentRowIndex].style.backgroundColor = "#FFFFD6";                 prevRowIndex = currentRowIndex;                 $('#<%= Label1.ClientID %>').text(currentRowIndex);                 $('#<%= hfParentContainer.ClientID %>').val(row);           $('#<%= hfCurrentRowIndex.ClientID %>').val(rowIndex);       }             $(function () {           RetainSelectedRow();       });             function RetainSelectedRow() {           var parent = $('#<%= hfParentContainer.ClientID %>').val();           var currentIndex = $('#<%= hfCurrentRowIndex.ClientID %>').val();           if (parent != null) {               ChangeRowColor(parent, currentIndex);           }       }          </script> </asp:content>   The ChangeRowColor() is the function that sets the background color of the selected row. It is also where we set the previous row and rowIndex values in HiddenFields.  The $(function(){}); is a short-hand for the jQuery document.ready function. This function will be fired once the page is posted back to the server that’s why we call the function RetainSelectedRow(). The RetainSelectedRow() function is where we referenced the current selected values stored from the HiddenFields and pass these values to the ChangeRowColor) function to retain the highlighted row. Finally, here’s the code behind part: protected void grdCustomer_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onclick", string.Format("ChangeRowColor('{0}','{1}');", e.Row.ClientID, e.Row.RowIndex)); } } The code above is responsible for attaching the javascript onclick event for each row and call the ChangeRowColor() function and passing the e.Row.ClientID and e.Row.RowIndex to the function. Here’s the sample output below:   That’s it! I hope someone find this post useful! Technorati Tags: jQuery,GridView,JavaScript,TipTricks

    Read the article

  • RegisterRequiresControlState can only be called before and during PreRender.

    - by user203127
    Hi When i am trying to export data from gridview to excelML I am getting error like RegisterRequiresControlState can only be called before and during PreRender. I dont know why it is happening. Please help me to sove this issue. Here is my sample code. I didnt implement any prerender method in my code. If i need to implement what should i write in that. protected void Button4_Click(object sender, System.EventArgs e) { ConfigureExport(); RadGrid1.ExportSettings.Excel.Format = Telerik.Web.UI.GridExcelExportFormat.ExcelML; CheckBox1.Checked = true; RadGrid1.ExportSettings.ExportOnlyData = true; RadGrid1.MasterTableView.ExportToExcel(); } public void ConfigureExport() { RadGrid1.ExportSettings.ExportOnlyData = CheckBox1.Checked; RadGrid1.ExportSettings.IgnorePaging = CheckBox2.Checked; RadGrid1.ExportSettings.OpenInNewWindow = CheckBox3.Checked; } protected void RadGrid1_ExcelMLExportRowCreated(object source, Telerik.Web.UI.GridExcelBuilder.GridExportExcelMLRowCreatedArgs e) { if (e.RowType == Telerik.Web.UI.GridExcelBuilder.GridExportExcelMLRowType.DataRow) { if (e.Row.Cells[0] != null && ((string)e.Row.Cells[0].Data.DataItem).Contains("U")) { e.Row.Cells[0].StyleValue = "MyCustomStyle"; e.Worksheet.Name = "comcast"; } } } protected void RadGrid1_ExcelMLExportStylesCreated(object source, Telerik.Web.UI.GridExcelBuilder.GridExportExcelMLStyleCreatedArgs e) { foreach (Telerik.Web.UI.GridExcelBuilder.StyleElement style in e.Styles) { if (style.Id == "headerStyle") { style.FontStyle.Bold = true; style.FontStyle.Color = System.Drawing.Color.Gainsboro; style.InteriorStyle.Color = System.Drawing.Color.Wheat; style.InteriorStyle.Pattern = Telerik.Web.UI.GridExcelBuilder.InteriorPatternType.Solid; } else if (style.Id == "itemStyle") { style.InteriorStyle.Color = System.Drawing.Color.WhiteSmoke; style.InteriorStyle.Pattern = Telerik.Web.UI.GridExcelBuilder.InteriorPatternType.Solid; } else if (style.Id == "alternatingItemStyle") { style.InteriorStyle.Color = System.Drawing.Color.LightGray; style.InteriorStyle.Pattern = Telerik.Web.UI.GridExcelBuilder.InteriorPatternType.Solid; } } Telerik.Web.UI.GridExcelBuilder.StyleElement myStyle = new Telerik.Web.UI.GridExcelBuilder.StyleElement("MyCustomStyle"); myStyle.FontStyle.Bold = true; myStyle.FontStyle.Italic = true; myStyle.InteriorStyle.Color = System.Drawing.Color.Gray; myStyle.InteriorStyle.Pattern = Telerik.Web.UI.GridExcelBuilder.InteriorPatternType.Solid; e.Styles.Add(myStyle); }

    Read the article

  • How to configure a GridView CommandField to trigger Full Page Update in UpdatePanel

    - by Frinavale
    I have 2 user controls on my page. One is used for searching, and the other is used for editing (along with a few other things). The user control that provides the search functionality uses a GridView to display the search results. This GridView has a CommandField used for editing (showEditButton="true"). I would like to place the GridView into an UpdatePanel so that paging through the search results will be smooth. The thing is that when the user clicks the Edit Link (the CommandField) I need to preform a full page postback so that the search user control can be hidden and the edit user control can be displayed. Edit: the reason I need to do a full page postback is because the edit user control is outside of the UpdatePanel that my GridView is in. It is not only outside the UpdatePanel, but it's in a completely different user control. I have no idea how to add the CommandField as a full page postback trigger to the UpdatePanel. The PostBackTrigger (which is used to indicate the controls cause a full page postback) takes a ControlID as a parameter; however the CommandButton does not have an ID...and you can see why I'm having a problem with this. Update on what else I've tried to solve the problem: I took a new approach to solving the problem. In my new approach, I used a TemplateField instead of a CommandField. I placed a LinkButton control in the TemplateField and gave it a name. During the GridView's RowDataBound event I retrieved the LinkButton control and added it to the UpdatePanel's Triggers. This is the ASP Markup for the UpdatePanel and the GridView <asp:UpdatePanel ID="SearchResultsUpdateSection" runat="server"> <ContentTemplate> <asp:GridView ID="SearchResultsGrid" runat="server" AllowPaging="true" AutoGenerateColumns="false"> <Columns> <asp:TemplateField> <HeaderTemplate></HeaderTemplate> <ItemTemplate> <asp:LinkButton ID="Edit" runat="server" Text="Edit"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:BoundField ...... </Columns> </asp:GridView> </ContentTemplate> </asp:UpdatePanel> In my VB.NET code. I implemented a function that handles the GridView's RowDataBound event. In this method I find the LinkButton for the row being bound to, create a PostBackTrigger for the LinkButton, and add it to the UpdatePanel's Triggers. This means that a PostBackTrigger is created for every "edit" LinkButton in the GridView Edit: this did not create a PostBackTrigger for Every "edit" LinkButton because the ID is the same for all LinkButtons in the GridView. Private Sub SearchResultsGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles SearchResultsGrod.RowDataBound If e.Row.RowType = DataControlRowType.Header Then ''I am doing stuff here that does not pertain to the problem Else Dim editLink As LinkButton = CType(e.Row.FindControl("Edit"), LinkButton) If editLink IsNot Nothing Then Dim fullPageTrigger As New PostBackTrigger fullPageTrigger.ControlID = editLink.ID SearchResultsUpdateSection.Triggers.Add(fullPageTrigger) End If End If End Sub And instead of handling the GridView's RowEditing event for editing purposes i use the RowCommand instead. Private Sub SearchResultsGrid_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles SearchResultsGrid.RowCommand RaiseEvent EditRecord(Me, New EventArgs()) End Sub This new approach didn't work at all because all of the LinkButtons in the GridView have the same ID. After reading the MSDN article on the UpdatePanel.Triggers Property I have the impression that Triggers can only be defined declaratively. This would mean that anything I did in the VB code wouldn't work. Any advise would be greatly appreciated. Thanks, -Frinny

    Read the article

  • SharePoint: Problem with BaseFieldControl

    - by Anoop
    Hi All, In below code in a Gird First column is BaseFieldControl from a column of type Choice of SPList. Secound column is a text box control with textchange event. Both the controls are created at rowdatabound event of gridview. Now the problem is that when Steps: 1) select any of the value from BaseFieldControl(DropDownList) which is rendered from Choice Column of SPList 2) enter any thing in textbox in another column of grid. 3) textchanged event fires up and in textchange event rebound the grid. Problem: the selected value becomes the first item or the default value(if any). but if i do not rebound the grid at text changed event it works fine. Please suggest what to do. using System; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace SharePointProjectTest.Layouts.SharePointProjectTest { public partial class TestBFC : LayoutsPageBase { GridView grid = null; protected void Page_Load(object sender, EventArgs e) { try { grid = new GridView(); grid.ShowFooter = true; grid.ShowHeader = true; grid.AutoGenerateColumns = true; grid.ID = "grdView"; grid.RowDataBound += new GridViewRowEventHandler(grid_RowDataBound); grid.Width = Unit.Pixel(900); MasterPage holder = (MasterPage)Page.Controls[0]; holder.FindControl("PlaceHolderMain").Controls.Add(grid); DataTable ds = new DataTable(); ds.Columns.Add("Choice"); //ds.Columns.Add("person"); ds.Columns.Add("Curr"); for (int i = 0; i < 3; i++) { DataRow dr = ds.NewRow(); ds.Rows.Add(dr); } grid.DataSource = ds; grid.DataBind(); } catch (Exception ex) { } } void tx_TextChanged(object sender, EventArgs e) { DataTable ds = new DataTable(); ds.Columns.Add("Choice"); ds.Columns.Add("Curr"); for (int i = 0; i < 3; i++) { DataRow dr = ds.NewRow(); ds.Rows.Add(dr); } grid.DataSource = ds; grid.DataBind(); } void grid_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { SPWeb web = SPContext.Current.Web; SPList list = web.Lists["Source for test"]; SPField field = list.Fields["Choice"]; SPListItem item=list.Items.Add(); BaseFieldControl control = (BaseFieldControl)GetSharePointControls(field, list, item, SPControlMode.New); if (control != null) { e.Row.Cells[0].Controls.Add(control); } TextBox tx = new TextBox(); tx.AutoPostBack = true; tx.ID = "Curr"; tx.TextChanged += new EventHandler(tx_TextChanged); e.Row.Cells[1].Controls.Add(tx); } } public static Control GetSharePointControls(SPField field, SPList list, SPListItem item, SPControlMode mode) { if (field == null || field.FieldRenderingControl == null || field.Hidden) return null; try { BaseFieldControl webControl = field.FieldRenderingControl; webControl.ListId = list.ID; webControl.ItemId = item.ID; webControl.FieldName = field.Title; webControl.ID = "id_" + field.InternalName; webControl.ControlMode = mode; webControl.EnableViewState = true; return webControl; } catch (Exception ex) { return null; } } } }

    Read the article

  • Binding DataTable To GridView, But No Rows In GridViewRowCollection Despite GridView Population?

    - by KSwift87
    Problem: I've coded a GridView in the markup in a page. I have coded a DataTable in the code-behind that takes data from a collection of custom objects. I then bind that DataTable to the GridView. (Specific problem mentioned a couple code-snippets below.) GridView Markup: <asp:GridView ID="gvCart" runat="server" CssClass="pList" AutoGenerateColumns="false" DataKeyNames="ProductID"> <Columns> <asp:BoundField DataField="ProductID" HeaderText="ProductID" /> <asp:BoundField DataField="Name" HeaderText="ProductName" /> <asp:ImageField DataImageUrlField="Thumbnail" HeaderText="Thumbnail"></asp:ImageField> <asp:BoundField DataField="Unit Price" HeaderText="Unit Price" /> <asp:TemplateField HeaderText="Quantity"> <ItemTemplate> <asp:TextBox ID="Quantity" runat="server" Text="<%# Bind('Quantity') %>" Width="25px"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Total Price" HeaderText="Total Price" /> </Columns> </asp:GridView> DataTable Code-Behind: private void View(List<OrderItem> cart) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add("Cart"); if (cart != null) { dt.Columns.Add("ProductID"); dt.Columns.Add("Name"); dt.Columns.Add("Thumbnail"); dt.Columns.Add("Unit Price"); dt.Columns.Add("Quantity"); dt.Columns.Add("Total Price"); foreach (OrderItem item in cart) { DataRow dr = dt.NewRow(); dr["ProductID"] = item.productId.ToString(); dr["Name"] = item.productName; dr["Thumbnail"] = ResolveUrl(item.productThumbnail); dr["Unit Price"] = "$" + item.productPrice.ToString(); dr["Quantity"] = item.productQuantity.ToString(); dr["Total Price"] = "$" + (item.productPrice * item.productQuantity).ToString(); dt.Rows.Add(dr); } gvCart.DataSource = dt; gvCart.DataBind(); gvCart.Width = 500; for (int counter = 0; counter < gvCart.Rows.Count; counter++) { gvCart.Rows[counter].Cells.Add(Common.createCell("<a href='cart.aspx?action=update&prodId=" + gvCart.Rows[counter].Cells[0].Text + "'>Update</a><br /><a href='cart.aspx?action='action=remove&prodId=" + gvCart.Rows[counter].Cells[0].Text + "/>Remove</a>")); } } } Error occurs below in the foreach - the GridViewRowCollection is empty! private void Update(string prodId) { List<OrderItem> cart = (List<OrderItem>)Session["cart"]; int uQty = 0; foreach (GridViewRow gvr in gvCart.Rows) { if (gvr.RowType == DataControlRowType.DataRow) { if (gvr.Cells[0].Text == prodId) { uQty = int.Parse(((TextBox)gvr.Cells[4].FindControl("Quantity")).Text); } } } Goal: I'm basically trying to find a way to update the data in my GridView (and more importantly my cart Session object) without having to do everything else I've seen online such as utilizing OnRowUpdate, etc. Could someone please tell me why gvCart.Rows is empty and/or how I could accomplish my goal without utilizing OnRowUpdate, etc.? When I execute this code, the GridView gets populated but for some reason I can't access any of its rows in the code-behind.

    Read the article

  • ASP.NET GridView - Cannot set the colour of the row during databind?

    - by Dan
    This is driving me NUTS! It's something that I've done 100s of time with a Datagrid. I'm now using a Gridview and I can't figure this out. I've got this grid: <asp:GridView AutoGenerateColumns="false" runat="server" ID="gvSelect" CssClass="GridViewStyle" GridLines="None" ShowHeader="False" PageSize="20" AllowPaging="True"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:Label runat="server" ID="lbldas" Text="blahblah"></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> And during the RowDataBound I've tried: Protected Sub gvSelect_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvSelect.RowCreated If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Attributes.Add("onMouseOver", "this.style.backgroundColor='lightgrey'") End If End Sub And it NEVER sets the row backcolor.. I've been successful in using: gridrow.Cells(0).BackColor = Drawing.Color.Blue But doing the entire row? NOPE! and it's driving me nuts.. does ANYONE have solution for me? And just for fun I put this on the SAME page: <asp:DataGrid AutoGenerateColumns="false" runat="server" ID="dgSelect" GridLines="None" ShowHeader="False" PageSize="20" AllowPaging="True"> <Columns> <asp:TemplateColumn> <ItemTemplate> <asp:Label runat="server" ID="lbldas" Text="blahblah"></asp:Label> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> And in the ItemDataBound I put: If Not e.Item.ItemType = ListItemType.Header And Not e.Item.ItemType = ListItemType.Footer Then e.Item.Attributes.Add("onMouseOver", "this.style.backgroundColor='lightgrey'") End If And it works as expected.. SO What am I doing wrong with the Gridview? UPDATE ************** I thought I'd post the resulting HTML to show that any styles aren't affecting this. Here's the gridview html: <div class="AspNet-GridView" id="gvSelect"> <table cellpadding="0" cellspacing="0" summary=""> <tbody> <tr> <td> <span id="gvSelect_ctl02_lbldas">blahblah</span> </td> </tr> </tbody> </table> </div> And here's the resulting Datagrid HTML: <table cellspacing="0" border="0" id="dgSelect" style="border-collapse:collapse;"> <tr onMouseOver="this.style.backgroundColor='lightgrey'"> <td> <span id="dgSelect_ctl03_lbldas">blahblah</span> </td> </tr> </table> See.. the main difference is the tag. It never gets set in the gridview.. and I don't know why.. I've traced through it.. and the code gets run.. :S

    Read the article

  • Using RIA DomainServices with ASP.NET and MVC 2

    - by Bobby Diaz
    Recently, I started working on a new ASP.NET MVC 2 project and I wanted to reuse the data access (LINQ to SQL) and business logic methods (WCF RIA Services) that had been developed for a previous project that used Silverlight for the front-end.  I figured that I would be able to instantiate the various DomainService classes from within my controller’s action methods, because after all, the code for those services didn’t look very complicated.  WRONG!  I didn’t realize at first that some of the functionality is handled automatically by the framework when the domain services are hosted as WCF services.  After some initial searching, I came across an invaluable post by Joe McBride, which described how to get RIA Service .svc files to work in an MVC 2 Web Application, and another by Brad Abrams.  Unfortunately, Brad’s solution was for an earlier preview release of RIA Services and no longer works with the version that I am running (PDC Preview). I have not tried the RC version of WCF RIA Services, so I am not sure if any of the issues I am having have been resolved, but I wanted to come up with a way to reuse the shared libraries so I wouldn’t have to write a non-RIA version that basically did the same thing.  The classes I came up with work with the scenarios I have encountered so far, but I wanted to go ahead and post the code in case someone else is having the same trouble I had.  Hopefully this will save you a few headaches! 1. Querying When I first tried to use a DomainService class to perform a query inside one of my controller’s action methods, I got an error stating that “This DomainService has not been initialized.”  To solve this issue, I created an extension method for all DomainServices that creates the required DomainServiceContext and passes it to the service’s Initialize() method.  Here is the code for the extension method; notice that I am creating a sort of mock HttpContext for those cases when the service is running outside of IIS, such as during unit testing!     public static class ServiceExtensions     {         /// <summary>         /// Initializes the domain service by creating a new <see cref="DomainServiceContext"/>         /// and calling the base DomainService.Initialize(DomainServiceContext) method.         /// </summary>         /// <typeparam name="TService">The type of the service.</typeparam>         /// <param name="service">The service.</param>         /// <returns></returns>         public static TService Initialize<TService>(this TService service)             where TService : DomainService         {             var context = CreateDomainServiceContext();             service.Initialize(context);             return service;         }           private static DomainServiceContext CreateDomainServiceContext()         {             var provider = new ServiceProvider(new HttpContextWrapper(GetHttpContext()));             return new DomainServiceContext(provider, DomainOperationType.Query);         }           private static HttpContext GetHttpContext()         {             var context = HttpContext.Current;   #if DEBUG             // create a mock HttpContext to use during unit testing...             if ( context == null )             {                 var writer = new StringWriter();                 var request = new SimpleWorkerRequest("/", "/",                     String.Empty, String.Empty, writer);                   context = new HttpContext(request)                 {                     User = new GenericPrincipal(new GenericIdentity("debug"), null)                 };             } #endif               return context;         }     }   With that in place, I can use it almost as normally as my first attempt, except with a call to Initialize():     public ActionResult Index()     {         var service = new NorthwindService().Initialize();         var customers = service.GetCustomers();           return View(customers);     } 2. Insert / Update / Delete Once I got the records showing up, I was trying to insert new records or update existing data when I ran into the next issue.  I say issue because I wasn’t getting any kind of error, which made it a little difficult to track down.  But once I realized that that the DataContext.SubmitChanges() method gets called automatically at the end of each domain service submit operation, I could start working on a way to mimic the behavior of a hosted domain service.  What I came up with, was a base class called LinqToSqlRepository<T> that basically sits between your implementation and the default LinqToSqlDomainService<T> class.     [EnableClientAccess()]     public class NorthwindService : LinqToSqlRepository<NorthwindDataContext>     {         public IQueryable<Customer> GetCustomers()         {             return this.DataContext.Customers;         }           public void InsertCustomer(Customer customer)         {             this.DataContext.Customers.InsertOnSubmit(customer);         }           public void UpdateCustomer(Customer currentCustomer)         {             this.DataContext.Customers.TryAttach(currentCustomer,                 this.ChangeSet.GetOriginal(currentCustomer));         }           public void DeleteCustomer(Customer customer)         {             this.DataContext.Customers.TryAttach(customer);             this.DataContext.Customers.DeleteOnSubmit(customer);         }     } Notice the new base class name (just change LinqToSqlDomainService to LinqToSqlRepository).  I also added a couple of DataContext (for Table<T>) extension methods called TryAttach that will check to see if the supplied entity is already attached before attempting to attach it, which would cause an error! 3. LinqToSqlRepository<T> Below is the code for the LinqToSqlRepository class.  The comments are pretty self explanatory, but be aware of the [IgnoreOperation] attributes on the generic repository methods, which ensures that they will be ignored by the code generator and not available in the Silverlight client application.     /// <summary>     /// Provides generic repository methods on top of the standard     /// <see cref="LinqToSqlDomainService&lt;TContext&gt;"/> functionality.     /// </summary>     /// <typeparam name="TContext">The type of the context.</typeparam>     public abstract class LinqToSqlRepository<TContext> : LinqToSqlDomainService<TContext>         where TContext : System.Data.Linq.DataContext, new()     {         /// <summary>         /// Retrieves an instance of an entity using it's unique identifier.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="keyValues">The key values.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual TEntity GetById<TEntity>(params object[] keyValues) where TEntity : class         {             var table = this.DataContext.GetTable<TEntity>();             var mapping = this.DataContext.Mapping.GetTable(typeof(TEntity));               var keys = mapping.RowType.IdentityMembers                 .Select((m, i) => m.Name + " = @" + i)                 .ToArray();               return table.Where(String.Join(" && ", keys), keyValues).FirstOrDefault();         }           /// <summary>         /// Creates a new query that can be executed to retrieve a collection         /// of entities from the <see cref="DataContext"/>.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <returns></returns>         [IgnoreOperation]         public virtual IQueryable<TEntity> GetEntityQuery<TEntity>() where TEntity : class         {             return this.DataContext.GetTable<TEntity>();         }           /// <summary>         /// Inserts the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Insert<TEntity>(TEntity entity) where TEntity : class         {             //var table = this.DataContext.GetTable<TEntity>();             //table.InsertOnSubmit(entity);               return this.Submit(entity, null, DomainOperation.Insert);         }           /// <summary>         /// Updates the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Update<TEntity>(TEntity entity) where TEntity : class         {             return this.Update(entity, null);         }           /// <summary>         /// Updates the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <param name="original">The original.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Update<TEntity>(TEntity entity, TEntity original)             where TEntity : class         {             if ( original == null )             {                 original = GetOriginal(entity);             }               var table = this.DataContext.GetTable<TEntity>();             table.TryAttach(entity, original);               return this.Submit(entity, original, DomainOperation.Update);         }           /// <summary>         /// Deletes the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Delete<TEntity>(TEntity entity) where TEntity : class         {             //var table = this.DataContext.GetTable<TEntity>();             //table.TryAttach(entity);             //table.DeleteOnSubmit(entity);               return this.Submit(entity, null, DomainOperation.Delete);         }           protected virtual bool Submit(Object entity, Object original, DomainOperation operation)         {             var entry = new ChangeSetEntry(0, entity, original, operation);             var changes = new ChangeSet(new ChangeSetEntry[] { entry });             return base.Submit(changes);         }           private TEntity GetOriginal<TEntity>(TEntity entity) where TEntity : class         {             var context = CreateDataContext();             var table = context.GetTable<TEntity>();             return table.FirstOrDefault(e => e == entity);         }     } 4. Conclusion So there you have it, a fully functional Repository implementation for your RIA Domain Services that can be consumed by your ASP.NET and MVC applications.  I have uploaded the source code along with unit tests and a sample web application that queries the Customers table from inside a Controller, as well as a Silverlight usage example. As always, I welcome any comments or suggestions on the approach I have taken.  If there is enough interest, I plan on contacting Colin Blair or maybe even the man himself, Brad Abrams, to see if this is something worthy of inclusion in the WCF RIA Services Contrib project.  What do you think? Enjoy!

    Read the article

< Previous Page | 1 2 3  | Next Page >