While binding the gridview throwing an error in a process? - javascript

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

Related

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

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);
}
}

Asp.net autocompleteextender selection issue with cursor point

I have use autocompleteextender for textbox autocomplete. I have written addition js for suggestion & value selection. Problem is after type ing some letter if I move my cursor from top to bottom then it doesn't select value where cursor is pointed. It selects value above cursor position. This problem only when cursor moves from top to bottom. Works fine when move bottom to top.
In following snapshot you can see where my cursor position & it highlighting value above.
<asp:TextBox ID="clientCode" runat="server" CssClass="field-pitch" ClientIDMode="Static"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="SearchClientCode"
ServicePath="~/auto.aspx" MinimumPrefixLength="1" CompletionInterval="100"
EnableCaching="false" CompletionSetCount="10" TargetControlID="clientCode"
ID="clientCodeExtender" runat="server" FirstRowSelected="false"
CompletionListCssClass="completionList" CompletionListItemCssClass="listItem"
CompletionListHighlightedItemCssClass="itemHighlighted"
OnClientPopulated="onClientPopulated" OnClientItemSelected="itemSelected"
BehaviorID="AutoCompleteEx"></asp:AutoCompleteExtender>
<script type="text/javascript">
function itemSelected(ev) {
var index = $find("AutoCompleteEx")._selectIndex;
if (index != -1) {
$find("AutoCompleteEx").get_element().value = $find("AutoCompleteEx").get_completionList().childNodes[index]._value;
}
else {
$find("AutoCompleteEx").get_element().value = '';
}
}
function onClientPopulated(sender, e) {
var List = $find("AutoCompleteEx").get_completionList();
for (i = 0; i < List.childNodes.length; i++) {
var _value = JSON.parse(List.childNodes[i]._value);
var abbr = _value[0];
var fullform = _value[1];
List.childNodes[i]._value = abbr;
List.childNodes[i].innerHTML = "<span>" + abbr + "(" + fullform + ")</span>"
}
}
</script>
code behind
[System.Web.Script.Services.ScriptMethod(), System.Web.Services.WebMethod()]
public static List<string> SearchClientCode(string prefixText, int count)
{
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings("conio").ConnectionString;
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT clientID, clientName FROM clientsDetails where (clientID like #SearchText)";
cmd.Parameters.AddWithValue("#SearchText", prefixText + Convert.ToString("%"));
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
MySqlDataReader sdr = cmd.ExecuteReader;
JavaScriptSerializer serializer = new JavaScriptSerializer();
while (sdr.Read) {
object[] item = new object[] {
sdr("clientID").ToString(),
sdr("clientName").ToString()
};
customers.Add(serializer.Serialize(item));
}
conn.Close();
return customers;
}
You should use the given parameters of the OnClientItemSelected method:
function itemSelected(source, eventArgs) {
$find("AutoCompleteEx").get_element().value = eventArgs.get_value();
}

How to disable function onclick programmatically button

this is my programmatically button, there is the error null pointer exception in logcat.
This is my way to loop the button.But the disable button for the button cannot function.When i click on "save" button the programmatically button will disable. is it my way to disable button is incorrect?
String CountQuery = "SELECT * FROM Category";
db = new DBController(getActivity());
SQLiteDatabase db2 = db.getReadableDatabase();
Cursor cursor1 = db2.rawQuery(CountQuery, null);
{
int num = cursor1.getCount();
Button[] valueB = new Button[num];
for (int i = 1; i < num; i++) {
String SelectQuery = "SELECT * FROM Category where CategoryID='" + i + "'";
db = new DBController(getActivity());
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor cursor = db1.rawQuery(SelectQuery, null);
if (cursor.moveToNext()) {
String categoryName = cursor.getString(1);
String coordinateX = cursor.getString(2);
String coordinateY = cursor.getString(3);
valueB[i] = new Button(getActivity());
valueB[i].setText("" + categoryName);
valueB[i].setId(i);
valueB[i].setOnTouchListener(this);
params = new RelativeLayout.LayoutParams(300, 100);
params.leftMargin = Integer.parseInt(coordinateX);
params.topMargin = Integer.parseInt(coordinateY);
final int finalI = i;
valueB[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "asdasd" + finalI, Toast.LENGTH_SHORT).show();
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
viewPager.setCurrentItem(finalI);
}
});
mRrootLayout.addView(valueB[i],params);
}
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (i[0] = 1; i[0] < num; i[0]++) {
valueB[i[0]].setOnTouchListener(null);
}
}
});
}
}
You can disable the onclick listener by using valueB[i].setOnClickListener(null);
you can disable the button by using setClickable method.
valueB[i].setClickable(false);
or you can user setEnabled method also like
valueB[i].setEnabled(false);

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>

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();
}));

Categories