How to convert c# list to Jquery e-calendar events? - javascript

I have a jquery events calendar (e-calendar) in the front end and retrieving the events from SharePoint calendar (c#), how can I convert this c# code to be displayed in the jquery e-calendar events?
Jquery events calendar:
https://github.com/jhonis/e-calendar
C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SPListItemCollection corporateCalendarListItems = GetCorporateCalendarItems();
if (corporateCalendarListItems != null) { AddCorporateCalendarEventsToUI(corporateCalendarListItems); }
}
}
private SPListItemCollection GetCorporateCalendarItems()
{
using (SPSite wadiSite = SPContext.Current.Site)
{
using (SPWeb wadiWeb = wadiSite.OpenWeb())
{
wadiWeb.AllowUnsafeUpdates = true;
// Fetch the List
SPList corporateCalendarList = wadiWeb.Lists.TryGetList("Corporate Calendar");
// Return the last item
if (corporateCalendarList != null)
{
DateTime todayDate = DateTime.Now;
string month = todayDate.ToString("MM");
string year = todayDate.ToString("yyyy");
string endOfMonthDate = year + "-" + month + "-30";
string startOfMonthDate = year + "-" + month + "-01";
SPQuery qry = new SPQuery();
qry.Query = #"<Where><And><And><Eq><FieldRef Name='Category' /><Value Type='Choice'>Holiday</Value></Eq><Geq><FieldRef Name='EventDate' /><Value Type='DateTime'>"+startOfMonthDate+"</Value></Geq></And><Leq><FieldRef Name='EventDate' /><Value Type='DateTime'>" + endOfMonthDate + "T12:00:00Z</Value></Leq></And></Where><OrderBy><FieldRef Name='EventDate' /></OrderBy>";
qry.ViewFields = #"<FieldRef Name='Title' /><FieldRef Name='EventDate' /><FieldRef Name='FileRef' /><FieldRef Name='EndDate' /><FieldRef Name='Category' />";
SPListItemCollection corporateCalendarListItems = corporateCalendarList.GetItems(qry);
return corporateCalendarListItems;
}
return null;
}
}
}
private void AddCorporateCalendarEventsToUI(SPListItemCollection corporateCalendarListItems)
{
List<CalendarEvent> calendarEvents = new List<CalendarEvent>();
foreach (SPListItem corporateCalendarListItem in corporateCalendarListItems)
{
CalendarEvent calendarEvent = new CalendarEvent();
calendarEvent.Title = corporateCalendarListItem["Title"].ToString();
if(corporateCalendarListItem["EventDate"] != null)
{
calendarEvent.StartDate = DateTime.Parse(corporateCalendarListItem["EventDate"].ToString());
}
if (corporateCalendarListItem["EndDate"] != null)
{
calendarEvent.EndDate = DateTime.Parse(corporateCalendarListItem["EndDate"].ToString());
}
calendarEvent.Category = "Test";
calendarEvent.AllDay = false;
calendarEvents.Add(calendarEvent);
}
}

Related

Same words are disappearing

I want to highlight a particular word and do a hover from gridview. My problem is if the word is repeated in the page the word is highlighted but other same words are disappearing form the text. Image for before and after highlight is attached. I have attached image of missing words before and after highlighting. Please help.
Page1.aspx
protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Pa"] = GridView3.SelectedRow.Cells[4].Text;
Session["paId"] = GridView3.SelectedRow.Cells[1].Text;
string sValue = ((HiddenField)GridView3.SelectedRow.FindControl("HiddenField1")).Value;
Session["panode"] = sValue;
Session["patt"] = GridView3.SelectedRow.Cells[5].Text.ToString().Trim('\n');
Response.Redirect("selectipc.aspx");
}
page2.aspx
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function () {
var searchWord = $("#hfWord").val();
var iframeHtml = $("#hfHTML").val();
var index = iframeHtml.indexOf(searchWord);
if (index >= 0) {
iframeHtml = iframeHtml.substring(0, index) + "<span id='lblHighlight' style='background-color: yellow;'>"
+ iframeHtml.substring(index, index + searchWord.length) + "</span>" + iframeHtml.substring(index + searchWord.length);
}
$('#frmDisplay').contents().find('body').html(iframeHtml);
if ($('#frmDisplay').contents().find('#lblHighlight').length > 0) {
$('#frmDisplay').contents().find('#lblHighlight')[0].scrollIntoView()
}
});
</script>
protected void Page_Load(object sender, EventArgs e)
{
//Session.Add("Logintype", Session["new"].ToString());
if (!this.IsPostBack)
{
if (Session["paId"] != null)
{
hfWord.Value = Session["pa"].ToString();
getPa();
//Session.Contents.Remove(Session["Pa"].ToString());
}
}
}
public void getPa()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString);
string panode = Session["panode"].ToString();
string pstext = Session["pa"].ToString();
string patext = Session["patt"].ToString();
string vc = (Convert.ToInt32(HttpContext.Current.Session["VCN"])).ToString();
SqlCommand cmd = new SqlCommand("select bn.vcFilePath from tblBookNodes bn inner join tbl_Pannotation pa on bn.iModuleId=pa.iNodeId where bn.iModuleId='" + panode + "' ", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
bytesp = (byte[])dr["vcFilePath"];
conn.Close();
}
getpa();
}
public void getpa()
{
string panId = Session["paId"].ToString();
string pstext = Session["pa"].ToString();
string patext = Session["patt"].ToString();
string fileName = panId.Replace(" ", "_") + ".htm";
//string returnpath = "File/htmlFile/";
string strPath = Server.MapPath("~/htmlFile/");
//if (Directory.Exists(strPath))
//{
// Directory.Delete(strPath, true);
//}
if (!Directory.Exists(strPath))
{
Directory.CreateDirectory(strPath);
}
//string pth = strPath;
string path = strPath + fileName;
var doc = new HtmlDocument();
string html = Encoding.UTF8.GetString(bytesp);
doc.LoadHtml(html);
StringWriter sw = new StringWriter();
var hw = new HtmlTextWriter(sw);
StreamWriter sWriter = new StreamWriter(path);
sWriter.Write(sw.ToString());
doc.Save(sWriter);
sWriter.Close();
//string fileContents = html;
string searchText = HttpUtility.HtmlEncode(pstext);
string newBookmarktag = "<style>font.tip {border - bottom: 1px dashed;text - decoration: none}font.tip:hover {cursor: help;position: sticky}font.tip span {display: none}font.tip:hover span {background-color:F0E6BC;text-align:center;color:Black;font-weight:bold;border: #c0c0c0 1px dotted;padding: 5px 20px 5px 5px;display: block;z - index: 1000;left: 0px;margin: 10px;position: absolute;top: 10px;text - decoration: none}</style><font style=background-color:yellow class=tip><a name=" + pstext + ">" + "<span>" + patext + "</span></a></font>";
// pstext = newBookmarktag;
html = html.Replace(searchText, newBookmarktag);
//hfHTML.Value = html;
System.IO.File.WriteAllText(path, html);
hfHTML.Value = File.ReadAllText(path);
//HiddenField1.Value = html;
Page page = (Page)HttpContext.Current.Handler;
MultiView control = ((IETM.select)(page)).MultiView1;
View View1 = (View)control.FindControl("View1");
HtmlControl ctrl = (HtmlControl)View1.FindControl("frmDisplay");
frmDisplay.Attributes.Add("src", HttpContext.Current.Request.Url + "/.." + "\\htmlFile\\" + fileName);
MultiView1.SetActiveView(View1);
}
indexOf return only first value position
better use split in this case
$(function () {
var searchWord = $("#hfWord").val();
var iframeHtml = $("#hfHTML").val();
iframeHtml = iframeHtml.split(searchWord).join("<span style='background-color: yellow;' class='lbl-highlight'>"+searchWord+"</span>");
$('#frmDisplay').contents().find('body').html(iframeHtml);
if ($('#frmDisplay').contents().find('.lbl-highlight').length > 0) {
$('#frmDisplay').contents().find('.lbl-highlight')[0].scrollIntoView()
}
});

hide and show function keeps refreshing the page

I'm trying to have a hide and show button
Whenever i click on the button, it works but also refreshes the page at the same time. I'm not sure what is causing the refresh. This is on aspx:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#buttontest").click(function () {
$("#hello").toggle();
});
});</script>
<button id="buttontest">test</button>
<div id="hello">hello</div>
Not sure if its the aspx.cs is causing the refreshing:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection myConnect = new SqlConnection(_connStr);
acct = new Account();
acct = (Account)Session["Account"];
if (!IsPostBack)
{
LoadCart();
DataBind();
string strCommandText = "SELECT * From Customer where Cust_Id = #Cust_Id";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#Cust_Id", 1);
//open connection and retrieve data by calling ExecuteReader
myConnect.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Lbl_FName.Text = dr["First_Name"].ToString();
Lbl_LName.Text = dr["Last_Name"].ToString();
Lbl_CNo.Text = dr["Contact_No"].ToString();
string addr1 = dr["Address"].ToString();
string addr2 = dr["Address2"].ToString();
address = new List<string>();
address.Add(dr["Address"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString());
address.Add(dr["Address2"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString());
//Ddl_Address.Text = dr["Address"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString();
//Ddl_Address.Text = dr["Address2"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString();
ddl_Addr.DataSource = address;
ddl_Addr.DataBind();
}
dr.Dispose();
dr.Close();
myConnect.Close();
//page load box retrieve
SqlConnection myConnect2 = new SqlConnection(_connStr);
string strCommandText2 = "SELECT * From Card_Details where Card_Id = #Card_Id";
myConnect2.Open();
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect2);
cmd2.Parameters.AddWithValue("#Card_Id", 1);
////open connection and retrieve data by calling ExecuteReader
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
CNo1 = dr2["Card_Number"].ToString();
CNo2 = dr2["Card_Number2"].ToString();
Session["CardNo1"] = CNo1;
Session["CardNo2"] = CNo2;
CNo = new List<string>();
CNo.Add(CNo1);
CNo.Add(CNo2);
ddl_CNo.DataSource = CNo;
ddl_CNo.DataBind();
//display when first run
Lbl_CardName.Text = dr2["Name_On_Card"].ToString();
Lbl_CardType.Text = dr2["Card_Type"].ToString();
Lbl_EDate.Text = dr2["Expired_Date"].ToString();
dr2.Dispose();
dr2.Close();
myConnect2.Close();
}
}
}
protected void ddl_CNo_SelectedIndexChanged(object sender, EventArgs e)
{
string cardNum1 = Session["CardNo1"].ToString();
string cardNum2 = Session["CardNo2"].ToString();
if (ddl_CNo.SelectedIndex == 0)
{
SqlConnection myConnect2 = new SqlConnection(_connStr);
string strCommandText2 = "SELECT Name_On_Card, Card_Type, Expired_Date From Card_Details where Card_Number = #Card_Number";
myConnect2.Open();
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect2);
cmd2.Parameters.AddWithValue("#Card_Number", cardNum1);
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
Lbl_CardName.Text = dr2["Name_On_Card"].ToString();
Lbl_CardType.Text = dr2["Card_Type"].ToString();
Lbl_EDate.Text = dr2["Expired_Date"].ToString();
}
dr2.Dispose();
dr2.Close();
// DataBind();
myConnect2.Close();
}
else if (ddl_CNo.SelectedIndex == 1)
{
SqlConnection myConnect3 = new SqlConnection(_connStr);
string strCommandText3 = "SELECT Name_On_Card2, Card_Type2, Expired_Date2 From Card_Details where Card_Number2 = #Card_Number2";
myConnect3.Open();
SqlCommand cmd3 = new SqlCommand(strCommandText3, myConnect3);
cmd3.Parameters.AddWithValue("#Card_Number2", cardNum2);
SqlDataReader dr3 = cmd3.ExecuteReader();
if (dr3.Read())
{
Lbl_CardName.Text = dr3["Name_On_Card2"].ToString();
Lbl_CardType.Text = dr3["Card_Type2"].ToString();
Lbl_EDate.Text = dr3["Expired_Date2"].ToString();
}
dr3.Dispose();
dr3.Close();
// DataBind();
myConnect3.Close();
}
}
protected void LoadCart()
{
gv_CartView.DataSource = ShoppingCart.Instance.Items;
gv_CartView.DataBind();
decimal total = 0.0m;
foreach (ShoppingCartItem item in ShoppingCart.Instance.Items)
{
total = total + item.TotalPrice;
}
decimal a = 2.0m;
decimal totalP = a + total;
Lbl_Subtotal.Text = total.ToString("C");
Lbl_TotalPrice.Text = totalP.ToString("C");
}
I'm still unfamiliar with all these, any help would be appreciated
EDIT: I've edited the button and javascript, it still caused a refresh
this looks like you might have button type as submit other wise this is not possible to happen
please make sure you added button as button not as submit button
Also please try to avoid
$("button").click(function () {
used specific button id
$("#btn_toggle").click(function () {
And you can also do.. in case if your button type is submit but you need to do return false.
$("#btn_toggle").click(function () {
$("#hello").toggle();
return false;
});
but make sure this will stop submit your from at server.
Replace server button with html button. i.e.
Replace
<asp:Button />
With
<input type="button" />
OR
do this:
$("button").click(function () {
$("#hello").toggle();
return false;
});
Try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#hello").toggle();
});
});</script>
<button>hello</button>
<div id="hello">hello</div>

MVC4 Client Site Split Dropdowns Date Validation

I've been trying to get some custom client site date validation working and so far I cannot seem to get it to work properly.
I have a custom date editor defined like this:
#model DateTime?
#{
if (Model.HasValue)
{
int day = Model.Value.Day;
int month = Model.Value.Month;
int year = Model.Value.Year;
}
List<SelectListItem> days = new List<SelectListItem>();
for (int i = 1; i <= 31; i++)
{
days.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Day == i});
}
List<SelectListItem> months = new List<SelectListItem>();
for (int i = 1; i <= 12; i++)
{
months.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Month == i});
}
List<SelectListItem> years = new List<SelectListItem>();
var minYear = DateTime.Now.Year - 100;
var maxYear = DateTime.Now.Year - 18;
for (int i = maxYear; i >= minYear; i--)
{
years.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Year == i });
}
}
#Html.DropDownList("days", days, "Day", new { #class="form__select" } )
#Html.DropDownList("months", months, "Month", new { #class="form__select" } )
#Html.DropDownList("years", years, "Year", new { #class="form__select" } )
And I have a custom validation attribute defined like this:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class DoBValidatorAttribute : ValidationAttribute, IClientValidatable
{
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
List<ModelClientValidationRule> clientRules = new List<ModelClientValidationRule>();
ModelClientValidationRule validDateRule = new ModelClientValidationRule
{
ErrorMessage = "Please enter a valid date.",
ValidationType = "validdate"
};
validDateRule.ValidationParameters.Add("dayelement", metadata.PropertyName + ".days");
validDateRule.ValidationParameters.Add("monthelement", metadata.PropertyName + ".months");
validDateRule.ValidationParameters.Add("yearelement", metadata.PropertyName + ".years");
clientRules.Add(validDateRule);
return clientRules;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime dateResult;
int day = Convert.ToInt32(validationContext.Items["days"]);
int month = Convert.ToInt32(validationContext.Items["months"]);
int year = Convert.ToInt32(validationContext.Items["years"]);
// Put date parts together and check is valid...
if (DateTime.TryParse(year + "/" + month + "/" + day, out dateResult))
{
return ValidationResult.Success;
}
// Not valid
return new ValidationResult(string.Format(ErrorMessageString, validationContext.DisplayName));
}
}
In order to (try) and wire all this together I also have this in my JavaScript:
jQuery.validator.unobtrusive.adapters.add(
'validdate', // notice this is coming from how you named your validation rule
['dayelement'],
['monthelement'],
['yearelement'],
function (options) {
options.rules['datepartcheck'] = options.params;
options.messages['datepartcheck'] = options.message;
}
);
jQuery.validator.addMethod('datepartcheck', function (value, element, params) {
var year = params[2];
var month = params[1];
var day = params[0];
var birthDate = year + '/' + month-1 + '/' + day;
var isValid = true;
try {
// datepicker is a part of jqueryUI.
// include it and you can take advantage of .parseDate:
$.datepicker.parseDate('yy/mm/dd', birthDate);
}
catch (error) {
isValid = false;
}
return isValid;
}, '');
I've put a breakpoint on all these methods but the GetClientValidationRules method is never called which I think means that the rules are never going to be applied to the HTML for one thing.
What am I doing wrong here? I just cannot figure it out. If I could I would ditch all of it and use a plain datepicker but the client is insistent on this format.
UPDATE
Just to be clear in the generated HTML the controls generated are three <select> inputs.
I'm wondering if it might be better to split this into three separate int properties on my model and use a range validator instead.

Append Text using jquery from checkboxlist

I am working in ASP.NET project. And my task is to append the Checkbox text to the TextBox. Checkboxes's text are bound from Database values in CheckBoxList.
protected void prbtn_Click(object sender, EventArgs e)
{
string ConnectionString = "Data Source=.;Initial Catalog=nci;Integrated Security=true";
SqlConnection myConn = new SqlConnection(ConnectionString);
List<string> minire = new List<string>();
string sql = "SELECT distinct PRIMARY_MINI_REGION FROM customers";
myConn.Open();
SqlCommand cmd = new SqlCommand(sql, myConn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
minire.Add(dt.Rows[0][0].ToString());
group12.DataSource = dt;
group12.DataTextField = "PRIMARY_MINI_REGION";
group12.DataValueField = "PRIMARY_MINI_REGION";
group12.DataBind();
string[] grpary = prgrp.Text.Split(';');
foreach (var items in grpary)
{
if (items != "")
{
li.Add(items.ToString());
if (li.Contains(items.ToString()))
{
group12.Items.FindByText(items.ToString()).Selected = true;
//group12.Items.FindByText(items.ToString()).Enabled = false;
}
}
}
}
Can any of you please help me how to do it in jquery.Currently i appended text using stringbuilder using C# as like
protected void group_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem l in group12.Items)
{
if (l.Selected)
{
li.Add(l.Text);
}
}
foreach (var i in li)
{
si.Append(i.ToString() + ";");
}
//if (prgrp.Text == "")
// prgrp.Text = si.ToString();
//else
prgrp.Text = si.ToString();
}
once i select checkbox means it have to append text.and once i unchecked it means,content have to be deleted from textbox
I guess this snippet helps you out:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// Repeat for all checked checkboxes:
$('input[type="checkbox"]:checked').each(function(){
// Get values:
var existingText = $("#output").html();
var textToAppend = $(this).val();
// Append seperator (';') if neccessary:
if(existingText != '')
{
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan"/>Jan
<input type="checkbox" value="Feb"/>Feb
<input type="checkbox" value="Mar"/>Mar
<input type="checkbox" value="Apr"/>Apr
<h2>Output:</h2>
<div id="output"></div>
$(document).ready(
$('.checkBoxCommunClass').on('click', function () {
var id = $(this).get(0).id;
if ($('input[id=' + id + ']:checked').length > 0)
$('#resultTextInput').val() = $('#resultTextInput').val() + $(this).val();
}));

While binding the gridview throwing an error in a process?

I am copying the selcted data from on grid to another on the click of a button. I am using postgre SQl for my apllication. Here is the link for the HTML. I am binding the data in as
NpgsqlDataAdapter adp;
NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["projop"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPrimaryGrid();
BindSecondaryGrid();
}
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
private void BindPrimaryGrid()
{
DataTable dt = new DataTable();
adp = new NpgsqlDataAdapter("select user_id, username,screen_name from users", conn);
dt = new DataTable("users");
adp.Fill(dt);
gvAll.DataSource = dt;
gvAll.DataBind();
After the selection of the data & button click as
protected void btnSubmit_Click(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords"] != null)
dt = (DataTable)ViewState["SelectedRecords"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gvAll.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < gvAll.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gvAll.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
dt = RemoveRow(gvAll.Rows[i], dt);
}
}
}
ViewState["SelectedRecords"] = dt;
}
private void SetData()
{
CheckBox chkAll = (CheckBox)gvAll.HeaderRow.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
if (ViewState["SelectedRecords"] != null)
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
for (int i = 0; i < gvAll.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
if (chk != null)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvAll.Rows[i].Cells[1].Text + "'");
chk.Checked = dr.Length > 0;
if (!chk.Checked)
{
chkAll.Checked = false;
}
}
}
}
}
Here while binding the data in function btnSubmit_Click via BindSecondaryGrid() showing an error on gvSelected.DataBind(); in function BindSecondaryGrid().
Error: DataBinding: 'HttpException - System.Data.DataRowView' does not contain a property with the name 'user_id'.
Edit: Add & Remove Codes
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["CustomerID"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["ContactName"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["Complete Name"] = gvRow.Cells[3].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
This is because your DataField specified in your GridView is incorrect. Let's try this.
<asp:BoundField DataField = "CustomerID" HeaderText = "Customer ID"
HtmlEncode = "false" />
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name"
HtmlEncode = "false" />
<asp:BoundField DataField = "CompleteName" HeaderText = "Complete Name"
HtmlEncode = "false" />
Please note that the DataField specified must match with the DataRow's name.
I am assuming your Datatable has column as highlighted with **:
dt.Rows[dt.Rows.Count - 1]["**CustomerID**"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["**ContactName**"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["**CompleteName**"] = gvRow.Cells[3].Text;
Let me know if this fixed this issue. Thanks

Categories