I tried to add data from data set to access database with TableAdapter.Update() method, but it doesn't function. Here is my code. I have DataGridView on my Windows Form, Table (Users) are binding to DataGridView.
private void btnScanGroups_Click(object sender, EventArgs e)
{
foreach (UserGroup group in g)
{
string groupName = group.Name;
string groupID = group.Link;
int userID = 1;
groupsTableAdapter.InsertGroupsQuery(groupName, groupID, userID);
text = text+"\n added "+groupName + " - " + groupID;
richTxtBoxStatus.Text = text;
}
groupsTableAdapter.Fill(facebookGroupAutoPostDBDataSet.Groups);
groupsBindingSource.EndEdit();
groupsTableAdapter.Update(facebookGroupAutoPostDBDataSet.Groups);
}
Related
I have a listbox with a list of items that get loaded when you navigate to a certain page. Then I have an on click that passes parameters to an AddProducts method. That method is what loops through all selected items and inserts values from the fields filled in as well as takes the values from the listItems and adds them as parameters to a stored procedure.
The problem I'm running into is that when looping through the listItems
if(selectedItem.Selected) is returning false, but in my method where I load the listbox I initialize a SelectedValue so I'm not sure why it's giving me the error message I have for no selected items. I was able to get it to work yesterday before I moved LoadListBoxCategories outside of LoadAddData but unsure as to why that would have any effect to if(listItem.Selected).
I'm relatively new to asp.net so any help/ explanation as to why my code isn't working is extremely appreciated. I've spent the last three days trying to figure this out and haven't found a solution that works.
Code:
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session[IS_LOGGED_IN] == null)
{
Response.Redirect("/utilities/companydata/login.aspx", true);
return;
}
gvTextInputs.RowEditing += new GridViewEditEventHandler(gvTextInputs_RowEditing);
if (!IsPostBack)
{
string pageId = Request.QueryString["pageid"];
string productId = Request.QueryString["productid"];
/* Add Mode */
if (!string.IsNullOrEmpty(pageId))
{
SetMode(MODE_ADD, "");
LoadAddData(pageId);
LoadListBoxCategories(pageId);
}
else if (!string.IsNullOrEmpty(productId))
{
string imageServer;
if (LoadProductData(productId, out imageServer))
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
SetMode(MODE_EDIT, imageServer);
SetImageServer(imageServer);
}
else
{
//TO DO - Return Error
}
}
}
else
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
}
}
Load ListBox:
private void LoadListBoxCategories(string pageId)
{
listBoxCategories.Visible = true;
//This gets query is so I can store the CompanyId and the CombinedValue data from pageId
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, (CAST(wp.pageId as varchar(200)) +'|'+ CAST(wp.productTypeId as varchar(200)) + '|' ) AS CombinedValue FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource connectionId = new SqlDataSource(DB_CONNECT, select);
connectionId.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)connectionId.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
string curCategoryProductTypeId = dView.Table.Rows[0]["CombinedValue"].ToString();
// EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId
// Lists All Categories #companyId has Active
string selectLoadData = "EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, selectLoadData);
conn.SelectParameters.Add("companyId", companyId);
lstCategoriesBox.Items.Clear();
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
// Pre-selects the value of the productTypeId you are trying to add a product for
// to send later run against a foreach insert in AddProduct()
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
testOutcomeCategory.InnerText = curCategoryProductTypeId;
lstCategoriesBox.DataSource = conn;
lstCategoriesBox.DataBind();
}
}
AddProduct:
private string AddProduct(string companyId, out string errMsg)
{
foreach (ListItem selectedItem in lstCategoriesBox.Items)
{
if (selectedItem.Selected)
{
// assign current productTypeId & pageId from selected Categories new CombinedValue column
string[] splitColumnValue = selectedItem.Value.Split('|');
string selectedPageId = splitColumnValue[0].ToString();
string selectedProductTypeId = splitColumnValue[1].ToString();
SqlDataSource connnection = new SqlDataSource(DB_CONNECT, "");
connnection.InsertCommand = "EXEC MCAdmin_AddProductFromClassic #pageId, #productTypeId, #productCode, #imgDirectory, #numSides, #sortOrder, #isActive, #template, #template2, #template3, #EditorJson, #MockupTemplateBase, #MockupTemplateTreatment, #BorderDefault ";
connnection.InsertParameters.Add("pageId", selectedPageId);
connnection.InsertParameters.Add("productTypeId", selectedProductTypeId);
connnection.InsertParameters.Add("productCode", txtProductCode.Text);
connnection.InsertParameters.Add("numSides", ddlNumSides.SelectedValue);
connnection.InsertParameters.Add("sortOrder", txtSortOrder.Text);
connnection.InsertParameters.Add("isActive", ddlActive.SelectedValue);
connnection.InsertParameters.Add("template", txtTemplate1.Text);
connnection.InsertParameters.Add("template2", txtTemplate2.Text);
connnection.InsertParameters.Add("template3", txtTemplate3.Text);
connnection.InsertParameters.Add("EditorJson", txtJson.Text);
connnection.InsertParameters.Add("MockupTemplateBase", txtMockupTemplateBase.Text);
connnection.InsertParameters.Add("MockupTemplateTreatment", txtMockupTemplateTreatment.Text);
connnection.InsertParameters.Add("BorderDefault", txtBorderDefault.Text);
/* Special Product Code for Upload Artwork Business Card */
if (txtProductCode.Text.ToUpper() == "BPFAH1-001-100")
{
connnection.InsertParameters.Add("imgDirectory", "/images/business-cards/general/");
}
else
{
connnection.InsertParameters.Add("imgDirectory", ddlImgDir.SelectedValue);
}
int result = connnection.Insert();
if (result > 0)
{
SqlDataSource connect = new SqlDataSource(DB_CONNECT, "");
connect.SelectCommand = "SELECT TOP 1 wtpProductId FROM WtpProducts ";
connect.SelectCommand = "WHERE productTypeId=#productTypeId AND pageId=#pageId DESC ";
connect.SelectParameters.Add("pageId", selectedPageId); //
connect.SelectParameters.Add("productTypeId", selectedProductTypeId); //
DataView dView = (DataView)connect.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string wtpProductId = dView.Table.Rows[0]["wtpProductId"].ToString();
errMsg = "";
return wtpProductId;
}
else
{
errMsg = "ERROR: Could not get productId of newly created Product.";
return "0";
}
}
else
{
errMsg = "ERROR: Could not add WtpProduct record to DB";
return "0";
}
}
else
{
errMsg = "ERROR: You must select a Category";
return "0";
}
}
errMsg = "ERROR: Did not make it into the foreach loop";
return "0";
}
OnClick method:
protected void OnClick_btnAddProduct(object sender, EventArgs e)
{
string pageId = Request.QueryString["pageid"];
testOutcomeCategory.InnerText = lstCategoriesBox.SelectedValue; // This proves that I have something selected!!!
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, baseImgDirectory, templateDirectory, wp.imageServer FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, select);
conn.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)conn.Select(DataSourceSelectArguments.Empty);
if(dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
if (!string.IsNullOrEmpty(pageId))
{
string errMsg;
string productId = AddProduct(companyId, out errMsg);
if(productId != "0")
{
Response.Redirect("/utilities/companydata/add-edit-wtp-product.aspx?productid=" + productId, true);
SetStatusMsg("Success", false);
}
else
{
SetStatusMsg(errMsg, true);
}
}
}
}
The list box instance is recreated on the server-side during the postback (as well as entire page). You do not set the selected items in the Page_Load event handler - if (!IsPostBack) goes to else branch. This is why you don't see them.
Ok,
lstCategoriesBox.Items.Clear();
Ok, above goes nuclear - blows out the list, blows out the selection.
Ok, that's fine
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
Ok, above adds a new item. Should be ok, but one should setup the lb BEFORE adding any data - including that "--select--" row.
It just makes sense to "setup" the lb and THEN start adding data, right?
However, But, if above works - ok, then lets keep going, but I would setup the lb before adding any rows of data. Say like this:
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
Now, the next line:
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
Ouch! - we just cleared the lb, and now we trying to set it to a value? You can't do that - the lb just been cleared, right? You would need to load up the lb first, and THEN you can set it to the selected value, right?
I might be missing something here, but that lb needs to be loaded up with valid data BEFORE you attempt to set the selected value?
To test first, change following
Outcome Category.InnerText = list CategoriesBox.SelectedValue;
to
Category.InnerText = Request.Form["CategoriesBox-ClientID"]
If the data is coming in correctly, the list view cleared or reloaded when between reload and click events the page.
UPDATE: I just figured it out! So stupid but when I check if(selectedItem.Selected) since I'm looping through the ListBox items it starts at the first index of the ListBox and since the first isn't selected then that if goes to the else block. Remove the else and it works fine
I have a text box which I manage its text changing event to filter the RadGrid:
private void txtJob_TextChanging(object sender, TextChangingEventArgs e)
{
this.gridCustomers.Columns["JobColumn"].FilterDescriptor = new FilterDescriptor
{
Operator = FilterOperator.Contains,
Value = txtJob.Text
};
}
I change JobColumn Text using CellFormatting Event:
private void gridCustomers_CellFormatting(object sender, CellFormattingEventArgs e)
{
if (e.Column.Name == "JobColumn")
e.CellElement.Text = db.tblJobs.First(x => x.JobID == Convert.ToInt32(e.Row.Cells[9].Value.ToString())).JobName;
}
I'm replacing Job ID with its Job Name in JobColumn, in that Text Box which I filtering RadGrid I'm searching for Job Name which is visible in RadGrid Now, but it will filter based on Job ID which is the default value before replacing.
So How can I filter a RadGrid Column based on its Text not Value?
For more information I'm binding a table like this to my girdview:
int JobID
nvarchar(10) Name
nvarchar(100) Address
.
.
.
And I have a table named Jobs like this:
int JobID
nvarchar(30) JobName
.
.
.
I need to get JobID from table one and in data binding (cell Formatting) replace the ID with its JobName in Jobs table.
Why I'm not selecting new and joining two table? because in that case I have not a grid view which can be edited easily, I must use Virtual Gird which is not my goal.
You are trying to hack the system. The correct approach in your case is to use GridVieWComboBoxColumn, which can be bound and DisplayMember and ValueMember to be specified. It also has FilterMode property to determine which field to use for filtering.
Read more GridViewComboBoxColumn | Telerik UI for WinForms Documentation
UPDATE
Here is a sample to get you started
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
DataTable mainTable = new DataTable();
mainTable.Columns.Add("JobID", typeof(int));
mainTable.Columns.Add("Name");
mainTable.Columns.Add("Address");
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
mainTable.Rows.Add(rand.Next(1,4), "Name " + i, "Address " + i);
}
DataTable jobsTable = new DataTable();
jobsTable.Columns.Add("JobID", typeof(int));
jobsTable.Columns.Add("JobName");
jobsTable.Rows.Add(1, "ABC ");
jobsTable.Rows.Add(2, "DFG");
jobsTable.Rows.Add(3, "XCV");
radGridView1 = new RadGridView() { Dock = DockStyle.Fill, AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill };
this.Controls.Add(radGridView1);
radGridView1.EnableFiltering = true;
radGridView1.DataSource = mainTable; //this will create all columns
radGridView1.Columns.Remove(radGridView1.Columns["JobId"]);
GridViewComboBoxColumn comboCol = new GridViewComboBoxColumn();
comboCol.DataSource = jobsTable;
comboCol.FieldName = "JobID"; //the name of the field in the main table to look for
comboCol.DisplayMember = "JobName"; //you want to see job names not ids
comboCol.ValueMember = "JobID";
comboCol.FilteringMode = GridViewFilteringMode.DisplayMember;
radGridView1.Columns.Insert(0, comboCol);
}
private void radButton1_Click(object sender, EventArgs e)
{
radGridView1.Columns["JobID"].FilterDescriptor = new FilterDescriptor
{
Operator = FilterOperator.Contains,
Value = "B"
};
}
dropdownlist selected value is not changing. although the string _month also contain the value but dropdownlist is not getting it.all other are working fine but only ddlMonth.selected value is not changing.i have assigned _month value to it but its not changing why? only ddlMonth is not changing all other are working fine why ddlmonth is not changing?
if (_objMonth.Contains("Month"))
{
string _Month = (string)_objMonth.GetData("Month");
ddlMonth.SelectedValue = _Month;
///here ddlMonth.selected value is not getting new value from _month
}
Other code is below
protected void Page_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack)
return;
try
{
OnLoad();
GetYears();
if (!string.IsNullOrEmpty(ddlYear.SelectedValue))
hYearId.Value = ddlYear.SelectedValue;
GetPeriods(Convert.ToInt32(hYearId.Value));
GetDepartment();
GetSection();
#region Get Selected login user department and section
ddldepartment.SelectedValue = CommonMethods.UserContext.EmployeeDeparmentID;
ddlSection.SelectedValue = CommonMethods.UserContext.EmployeeSectionID;
#endregion
ddldepartment_SelectedIndexChanged(null, null);
ddlemp_SelectedIndexChanged(null, null);
string name = Request.QueryString["id"] as string;
#region Create Cache object
ICacheManager _objYear = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objMonth = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objDepartment = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objSection = CacheFactory.GetCacheManager();//Create cache object
#endregion
if (Request.QueryString["ClickTag"]!=null)
{
#region set Cached items
if (Request.QueryString["ClickTag"].ToString() == "1")
{
if (_objYear.Contains("Year"))
{
string _Year = (string)_objYear.GetData("Year");
ddlYear.SelectedValue = _Year;
}
if (_objMonth.Contains("Month"))
{
string _Month = (string)_objMonth.GetData("Month");
ddlMonth.SelectedValue= _Month;
}
if (_objDepartment.Contains("Department"))
{
string _Department = (string)_objDepartment.GetData("Department");
ddldepartment.SelectedValue= _Department;
}
if (_objSection.Contains("Section"))
{
string _Section = (string)_objSection.GetData("Section");
ddlSection.SelectedValue = _Section;
}
}
#endregion
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(ddlMonth.SelectedValue))
{
hClpid.Value = ddlMonth.SelectedValue.Split(',')[0];
Session["Startdate"] = ddlMonth.SelectedValue.Split(',')[2];
Session["EndDate"] = ddlMonth.SelectedValue.Split(',')[3];
ddldepartment_SelectedIndexChanged(null, null);
ddlemp_SelectedIndexChanged(null, null);
if (ddlSection.SelectedIndex > 0)
ddlSection_SelectedIndexChanged(null, null);
}
}
void GetPeriods(int _year)
{
IBLCalenderPeriod _bl = (IBLCalenderPeriod)SetupBLFactory.GetCalenderPeriod();
DataSet _ds = (DataSet)_bl.GetPeriodIdsByYear(_year).GetMaster();
_ds.Tables[0].Columns.Add("ID");
foreach (DataRow _dr in _ds.Tables[0].Rows)
{
_dr["ID"] = _dr["CLP_ID"] + "," + _dr["clp_activeperiod"] + "," + _dr["CLP_DATESTART"] + "," + _dr["CLP_DATEEND"] + "";
}
ddlMonth.DataSource = _ds.Tables[0];
ddlMonth.DataTextField = "CLP_DESCRIPTION";
ddlMonth.DataValueField = "ID";
ddlMonth.DataBind();
foreach (DataRow _dr in _ds.Tables[0].Rows)
{
if (_dr["clp_activeperiod"] != null)
if (_dr["clp_activeperiod"].ToString() == "1")
{
ddlMonth.SelectedValue = _dr["ID"].ToString();
hClpid.Value = ddlMonth.SelectedValue.Split(',')[0];
Session["Startdate"] = ddlMonth.SelectedValue.Split(',')[2];
Session["EndDate"] = ddlMonth.SelectedValue.Split(',')[3];
break;
}
else
{
ddlMonth.SelectedIndex = 0;
hClpid.Value = "0";
}
}
}
I think you are setting a value in ddlMonth but ddlMonth do not have that binded value.. Try to bind list of values in your ddlMonth before setting a value to it
Please next time format the code before posting.
For the problem I think the solution is to put the region where you set the SelectedValue inside an
if(!isPostback){...}
I suggest you to take a look to the documentation about page lifecycle, because the explanation is that the Page_Load in executed not only the first time you load a page, but also for every postback (if you don't use the if(!isPostback){...}
i am working on a project and i have a gridview and a radiobutton in gridview and what i want is,i want to send the selected rows value to database on the click of the button but i am getting an error as object reference not set to the instance of an object.
As my code is
cs code on the click of the button
protected void btn_selectgridview_Click(object sender, EventArgs e)
{
int k = 0;
//Checkther whether atleast one check box is selected or not
for (int i = 0; i <=gvrepair_details.Rows.Count-1; i++)
{
GridViewRow row = gvrepair_details.Rows[i];
RadioButton rb = (RadioButton)row.FindControl("CheckBox1");
if (rb.Checked == true)
{
k++;
}
}
if (k == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),Guid.NewGuid().ToString(), "<script language=JavaScript>alert('select the value in grid');</script>");
return;
}
for (int i = 0; i <=gvrepair_details.Rows.Count-1; i++)
{
string bookname = gvrepair_details.Rows[i].Cells[1].Text;
string categoryname = gvrepair_details.Rows[i].Cells[2].Text;
string subcategory =gvrepair_details.Rows[i].Cells[3].Text;
string shelf_no = gvrepair_details.Rows[i].Cells[4].Text;
string isbn = gvrepair_details.Rows[i].Cells[5].Text;
string edition = gvrepair_details.Rows[i].Cells[6].Text;
string status = gvrepair_details.Rows[i].Cells[7].Text;
GridViewRow row = gvrepair_details.Rows[i];
RadioButton rb = (RadioButton)row.FindControl("CheckBox1");
if (rb.Checked == true)
{
InsertData(bookname, categoryname, subcategory, shelf_no, isbn, edition, status);
}
}
}
void InsertData(String bookname, String categoryname, String subcategory,String shelf_no,String isbn,String edition,String status)
{
try
{
sql = "insert into library_repair(bookname, categoryname, subcategoryname, shelf_no, isbn, edition, status)values('" +bookname+ "','" +categoryname+ "','" +subcategory+ "','"+shelf_no+"','"+isbn+"','"+edition+"','"+status+"')";
ds = obj.openDataset(sql, Session["SCHOOLCODE"].ToString());
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
I reformulated you first function (Code may contains syntax error since haven't run it):
protected void btn_selectgridview_Click(object sender, EventArgs e)
{
int k = 0;
int checkBoxColumnIndex = 2; //Here you should specify the cell containing the checkBox
foreach (GridViewRow item in gvrepair_details.Rows)
{
RadioButton rb = (RadioButton)item.Cells[checkBoxColumnIndex].FindControl("CheckBox1");
if (rb != null && rb.Checked) //Check if rb is null
{
k++;
string bookname = item.Cells[1].Text;
string categoryname = item.Cells[2].Text;
string subcategory = item.Cells[3].Text;
string shelf_no = item.Cells[4].Text;
string isbn = item.Cells[5].Text;
string edition = item.Cells[6].Text;
string status = item.Cells[7].Text;
InsertData(bookname, categoryname, subcategory, shelf_no, isbn, edition, status);
}
}
//Checkther whether atleast one check box is selected or not
if (k == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script language=JavaScript>alert('select the value in grid');</script>");
return;
}
}
Note the checkBoxColumnIndex. CheckBox1 index should be provided.
try this
if (((RadioButton)gvrepair_details.Rows[i].FindControl("CheckBox1")).Checked == true)
{
k++;
}
instead of
if (rb.Checked == true)
{
k++;
}
I have a form that has 2 dropdowns.
First dropdown and with ajax I fill the second dropdown onclick of button I store both these values in database.
Now i want to display the stored value in the dropdown bt i am nt understanding how shall i do this.
public void ddldropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
IApplicationContext ctx = ContextRegistry.GetContext();
IServices reg = (IServices)ctx.GetObject("Services");
Int16 ID = Convert.ToInt16(ddldropdown1.SelectedValue);
if (ID != 0)
{
IList listDate = reg.getDateList(ID);
int Count = listDate.Count;
for (int i = 0; i < Count; i++)
{
DateList obj = new DateList();
obj = (DateList)listDate[i];
string strDate = obj.selectDate.Day.ToString() + "/" + obj.selectDate.Month.ToString() + "/" + obj.selectDate.Year.ToString();
ddlDatedropdown.Items.Add(new ListItem(strDate, strDate));
}
}
}
//Code for Save button
protected void btnSave_Click(object sender, EventArgs e)
{
IApplicationContext ctx = ContextRegistry.GetContext();
IServices reg = (IServices)ctx.GetObject("Services");
int Dropdown1ID = Convert.ToInt32(ddldropdown1.SelectedValue);
string strDate = "";
strDate = ddlDatedropdown.SelectedValue.Split("/".ToCharArray())[1] + "/" + ddlDatedropdown.SelectedValue.Split("/".ToCharArray())[0] + "/" + ddlDatedropdown.SelectedValue.Split("/".ToCharArray())[2];
DateTime SelectDate = Convert.ToDateTime(strDate);
if(reg.confirmGDPIRegistration(Dropdown1ID , strDate))
{
messagebox.show("saved");
}
}
Inside the aspx Page i hav declared the second dropdown like this -
<asp:DropDownList ID="Datedropdown" runat="server">
<asp:ListItem Value = "-- Select --">-- Select --</asp:ListItem>
</asp:DropDownList>
Inorder to display i do this-
DataSet ds = reg.getData(PID);
if (ds.Tables.Count> 0)
{
ddldropdown1.SelectedValue = ds.Tables[0].Rows[0]["ID"].ToString();
//how to do this for date????
}
For the First Dropdown i can fetch the value, but my question is:
How can I fetch and display the date for the second dropdown?